【问题标题】:JSON post request don't workJSON 发布请求不起作用
【发布时间】:2015-07-22 18:33:05
【问题描述】:

我正在使用此代码但无法正常工作。 NSLog in post 和 get 方法为空。 我需要发布原始数据。我在 Body - raw 中编写参数,它可以工作(Chrome- POSTMAN)。

这个参数:

[
    {
    "user":    "admin",
    "pass":    "admin123",
    "delete_book": 0,
    "add_book": false,
    "read_book": false,
    "bookprice": 0,
    "person": "",
    "book": 0  
    }
]

我的 post 方法代码:

 NSString * paramters = [[NSString alloc] initWithFormat:@"[{\"user\": \"admin\",\"pass\": \"admin123\",\"delete_book\": \"0\",\"add_book\": \"false\",\"read_book\": \"false\",\"bookprice\": \"0\",\"person\": \"\",\"book\": \"0\"}]"];
    NSError *error;

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
    NSURL *url = [NSURL URLWithString:@"http://www.xxxxxxxxx.com"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:60.0];

    [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request addValue:@"application/json" forHTTPHeaderField:@"Accept"];

    [request setHTTPMethod:@"POST"];

  //  NSData *postData = [NSJSONSerialization dataWithJSONObject:paramters options:0 error:&error];
  NSData *postData = [paramters dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:postData];


    NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if([data length] > 0)
                {
                    NSError *err = nil;
                    NSDictionary *dictResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&err];
                    NSLog(@"Result : %@",dictResponse);
                }
                else{
                    NSLog(@"Failed To Get Response.");
                }
            });

    }];

    [postDataTask resume];

我解决了问题 这是解决方案: NSData *postData = [参数 dataUsingEncoding:NSUTF8StringEncoding];

【问题讨论】:

  • 发帖请求的格式是否正确?
  • 我不知道,我知道我需要 JSON 发布请求。
  • 我的意思是网址格式正确吗?
  • 如我所见,您试图在 url.com 中发布没有意义的参数。
  • 我的代码中有真实的 URL,这是示例。

标签: objective-c iphone json xcode post


【解决方案1】:

试试这个:我想你错过了 & 在帖子字符串的开头,就在用户参数之前

NSString  *post = [NSString stringWithFormat:@"&user=admin&pass=admin123&delete_book=0&add_book=false&read_book=false&bookprice=0&person=0&book=0"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://your-url"]]];

[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

 NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

     //check here if nsdata is nil or not
      NSLog(@"nsdata is %@",data);
    //if it is nil , then there should be something wrong with the url

    NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"requestReply: %@", requestReply);

    //convert into JSON
     NSError *e = nil;
        NSData *jsonData = [requestReply dataUsingEncoding:NSUTF8StringEncoding];

        NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:jsonData options: NSJSONReadingMutableContainers error: &e];

        NSLog(@"json is %@",JSON); //check json here
}] resume];

编辑:邮递员参考:

【讨论】:

  • requestReply 仍为空。
  • 尝试 nslog NSdata 并检查它是否为空
  • 使用 NSUTF8StringEncoding 编码
  • 当我的NSLog POSTDATA我接收
  • 将回复字符串转换为json并尝试NSLog json回复
【解决方案2】:

试试这个代码... 希望对你有用

-(void)postServerCall{
        NSString *postString = [NSString stringWithFormat:@"user=admin&pass=admin123&delete_book=0&add_book=false&read_book=false&bookprice=0&person=0&book=0"];

        NSOperationQueue *backgroundQueue = [[NSOperationQueue alloc] init];

        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://PostUrl.com"]]];

        [request setHTTPMethod:@"POST"];
        [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];

        [NSURLConnection sendAsynchronousRequest:request queue:backgroundQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){

            if (error)
            {
                NSLog(@"%@",[error localizedDescription]);
            }
            else
            {
                NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                NSLog(@"result....%@",result);
            }
        }];
        }

【讨论】:

    【解决方案3】:
    + (void)callPOSTAPIWithParams:(NSDictionary *)params andCompletionHandler:(void(^)(NSDictionary *result))completionHandler
    {
        NSURL *URL = [NSURL URLWithString:[NSString stringWithFormat:@"%@",<Your HOST API URL>]];
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:URL];
    
        NSURLSession *session = [NSURLSession sharedSession];
    
        NSError *err = nil;
        NSData *requestData = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:&err];
        //    NSLog(@"%@",[[NSString alloc] initWithData:requestData encoding:NSUTF8StringEncoding]);
        [request setHTTPMethod:@"POST"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        //    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[requestData length]] forHTTPHeaderField:@"Content-Length"];
        [request setHTTPBody:requestData];
    
        NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                                completionHandler:
                                      ^(NSData *data, NSURLResponse *response, NSError *error)
                                      {
                                          dispatch_async(dispatch_get_main_queue(), ^{
                                              if([data length] > 0)
                                              {
                                                  NSError *err = nil;
                                                  NSDictionary *dictResponse = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&err];
                                                  NSLog(@"Result : %@",dictResponse);
                                              }
                                              else{
                                                  NSLog(@"Failed To Get Response.");
                                              }
                                          });
                                      }];
    
        [task resume];
    }
    

    How to use

    NSDictionary *paramters = @{@"param1":@"value1"};
    [Global callPOSTAPIUsingSessionWithParams:paramters andCompletionHandler:^(NSDictionary *result) {
    NSLog(@"check result");
    }];
    

    【讨论】:

    • 显示 -> 结果:(空)。我有像 NSDictionary *paramters = @{@"user":@"admin",@"pass":@"admin123"...}; 这样的参数
    • 检查你的api是否支持post和json,用“POSTMAN”工具验证
    猜你喜欢
    • 2017-01-28
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 2015-11-13
    • 2019-01-27
    相关资源
    最近更新 更多