0
我有點不安,我通常使用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進行身份驗證有關?
狀態代碼是在這裏一大線索。狀態碼403是「[Forbidden](http://httpstatus.es/403)」。如果認證是問題,你會期望一個401.向我們展示你的cURL命令可能是有用的。 – neilco
您缺少標題字段。請求開發該API的團隊中的所有關鍵值標題和正文 – amar