获取错误时NSURLConnection结果不同

时间:2013-03-21 09:07:24

标签: objective-c nsurlconnection nsurlrequest

我正在使用-[NSURLConnection initWithRequest...]连接到服务器, 当服务器端出现故障时,它将响应错误400,并在正文中显示消息。 当没有错误时,我可以在didReceiveData中获取响应数据。但是当服务器返回错误400时,我在didReceiveData中没有收到任何错误消息。

但是,如果我使用-[NSURLConnection sendSynchronousRequest...]来执行相同的请求 我从sendSynchronousRequest的返回值中获取错误数据。

我想从didReceiveData获取错误消息,但我不知道为什么我无法得到它。 这有什么不同,有人可以帮助我吗?

这样我就可以收到错误消息:

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]);
}

2 个答案:

答案 0 :(得分:1)

使用此委托方法处理此类错误。

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
      NSLog(@" Failed with error---%@",error);
}

答案 1 :(得分:1)

我想我发现它发生了什么, 当我在didReceiveResponse中收到错误状态代码时, 我立即尝试获取数据并取消连接, 但这是错的, 因为didReceiveData仍然在didReceiveResponse之后接收。

非常感谢!