2016-02-25 58 views
0

我正在尝试做一个简单的POST请求。但是,结果在Chrome的POSTMAN插件和iOS模拟器中显得不同。NSData正在返回0字节

这里是邮差快照:

enter image description here

enter image description here

正如你所看到的,我得到了retun JSON数据。

这里是我的代码做POST请求:

NSError *error; 
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; 
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil]; 
    NSURL *url = [NSURL URLWithString:kPostURL]; 
    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"]; 


    NSString *params =[[NSString alloc] initWithFormat:@"fname=%@&lname=%@&email=%@&password=%@&switchid=%d&didflag=%@",fname,lname,email,pass,switchid,flag]; 

    [request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]]; 
    NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 

     NSLog(@"response is %@",response); 
     NSLog(@"erros is %@",error); 

     NSMutableDictionary * innerJson = [NSJSONSerialization 
              JSONObjectWithData:data options:kNilOptions error:&error 
              ]; 
     NSLog(@"JSON data is %@",innerJson); 

    }]; 

    [postDataTask resume]; 

,当我尝试在调试器打印的价值观,我得到

JSONnullNSData0bytes。但我得到了status code as 200,这是成功的。

这里是响应我得到:

 { status code: 200, headers { 
    Connection = "Keep-Alive"; 
    "Content-Length" = 0; 
    "Content-Type" = "text/html"; 
    Date = "Thu, 25 Feb 2016 02:04:02 GMT"; 
    "Keep-Alive" = "timeout=5"; 
    Server = "Apache/2.4.12"; 
    "X-Powered-By" = "PHP/5.5.30"; 
} } 

为什么我得到的NSData为0字节?

回答

1

在chrome中的请求中,您的参数为URL params。在ObjC版本中,您将添加参数作为帖子的一部分。

的,而不是添加了PARAMS作为身体的一部分:

[request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]]; 

其添加为查询的一部分:

NSURL *url = [NSURL URLWithString:[kPostURL stringByAppendingFormat:@"?%@", params]]; 
+0

感谢。有效。 –