我-[NSURLConnection initWithRequest...]
用来连接服务器,当服务器端出现故障时,它会响应错误 400 并在正文中显示一条消息。在没有错误的情况下,我可以在 didReceiveData 中获取响应数据。但是当服务器返回错误 400 时,我在 didReceiveData 中没有收到任何错误消息。
但是,如果我-[NSURLConnection sendSynchronousRequest...]
用来执行相同的请求,我会从sendSynchronousRequest
的返回值中获取错误数据。
我想从 didReceiveData 获取错误消息,但我不知道为什么我不能得到它。do之间有什么不同,有人可以帮助我吗?
这样我可以得到错误信息:
NSURL *url = [NSURL URLWithString:@"http://devapi.xxx.com/v1/debug/error"];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] initWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:240] autorelease];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
NSLog(@"STATUS:%d", [((NSHTTPURLResponse *)response) statusCode]);
NSLog(@"ERROR:%@", error);
这样我就无法得到它:
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://devapi.xxx.com/v1/debug/error"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:240] autorelease];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
urlConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(@"statusCode:%d",((NSHTTPURLResponse *)response).statusCode);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[receivedData appendData:data];
NSLog(@"DATA:%@",[NSString stringWithCString:[receivedData bytes] encoding:NSASCIIStringEncoding]);
}