iOS NSURLConnection JSON失败

问题描述:

我有点不安,我通常使用MKNetworkKit或某个库,但是这次我不得不手动执行HTTP请求,因为我想设置正文数据。iOS NSURLConnection JSON失败

这是我的要求:

NSData* data = [NSJSONSerialization dataWithJSONObject:questionDict 
               options:NSJSONWritingPrettyPrinted error:Nil]; 

NSString* aStr; 
aStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 
[request setURL:fullAPIURL_URL]; 
[request setHTTPMethod:@"POST"]; 
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; 
[request setHTTPBody:[NSData dataWithContentsOfFile:aStr]]; 

NSLog(@"Data: %@",aStr); 

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
[connection start]; 

这是一个HTTPS的SSL如果这能帮助?

然后我处理这样的响应;

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace { 
    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]; 
} 

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge { 

    [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge]; 
} 

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 
    NSLog(@"Response: %@",response); 
} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 
    [receivedData_ appendData:data]; 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection { 
    NSLog(@"Succeeded! Received %d bytes of data", [receivedData_ length]); 
    NSString *responeString = [[NSString alloc] initWithData:receivedData_ 
                encoding:NSUTF8StringEncoding]; 
    NSLog(@"Response: %@",responeString); 

    // Assume lowercase 
    if ([responeString isEqualToString:@"true"]) { 
     // Deal with true 
     return; 
    } 
    // Deal with an error 
} 

我只是在日志中得到这个;

{ status code: 403, headers { 
    "Cache-Control" = "no-cache, must-revalidate"; 
    Connection = close; 
    "Content-Length" = 48; 
    "Content-Type" = "application/json"; 
    Date = "Mon, 06 Jan 2014 10:22:40 GMT"; 
    Expires = "Mon, 06 Jan 2014 10:22:40 GMT"; 
    P3P = "policyref=\"/w3c/p3p.xml\", CP=\"ALL DSP COR CURa OUR IND COM NAV CNT\""; 
    Pragma = "no-cache"; 
    Server = Apache; 
    "X-Powered-By" = PleskLin; 
} } 
Succeeded! Received 0 bytes of data 
Response: 

赞赏任何帮助,我已经测试了这个使用卷曲客户端和它的作品,因为它应该做的。我认为这与使用SSL进行身份验证有关?

+0

状态代码是在这里一大线索。状态码403是“[Forbidden](http://httpstatus.es/403)”。如果认证是问题,你会期望一个401.向我们展示你的cURL命令可能是有用的。 – neilco

+0

您缺少标题字段。请求开发该API的团队中的所有关键值标题和正文 – amar

我已经修复了我自己的问题。对于其他人来说,它是下面一行;

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

我错过了 “dataUsingEncoding”