在Objective-C中使用NSURLConnection
解析JSON时,如果遇到服务器返回的错误消息,通常是因为HTTP请求返回了一个非成功的状态码(例如4xx或5xx)。为了获取服务器返回的错误消息,你需要检查HTTP响应的状态码,并从响应体中读取错误详情。
以下是一个简单的示例,展示如何使用NSURLConnection
发送请求并在遇到错误时获取服务器的错误消息:
#import <Foundation/Foundation.h>
@interface NetworkClient : NSObject <NSURLConnectionDelegate>
- (void)sendRequestWithURL:(NSURL *)url;
@end
@implementation NetworkClient
- (void)sendRequestWithURL:(NSURL *)url {
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
}
#pragma mark - NSURLConnectionDelegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if (httpResponse.statusCode >= 400) {
// 请求失败,准备读取错误消息
[connection cancel];
NSError *error = [NSError errorWithDomain:@"HTTPErrorDomain" code:httpResponse.statusCode userInfo:nil];
[self handleError:error];
}
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// 如果之前检测到错误状态码,这里可以读取错误消息
NSString *errorString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"Server error message: %@", errorString);
}
- (void)handleError:(NSError *)error {
// 处理错误,例如显示错误消息给用户
NSLog(@"Error: %@", error);
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
NetworkClient *client = [[NetworkClient alloc] init];
NSURL *url = [NSURL URLWithString:@"https://example.com/api"];
[client sendRequestWithURL:url];
}
return 0;
}
在这个示例中,NetworkClient
类负责发送网络请求并处理响应。当connection:didReceiveResponse:
方法被调用时,它会检查HTTP响应的状态码。如果状态码表示错误(例如4xx或5xx),它会取消连接并调用handleError:
方法来处理错误。
connection:didReceiveData:
方法会在接收到数据时被调用。如果之前检测到错误状态码,这里可以读取错误消息。
请注意,NSURLConnection
已经在iOS 9中被标记为废弃,建议使用NSURLSession
来替代。以下是使用NSURLSession
的类似示例:
#import <Foundation/Foundation.h>
@interface NetworkClient : NSObject
- (void)sendRequestWithURL:(NSURL *)url;
@end
@implementation NetworkClient
- (void)sendRequestWithURL:(NSURL *)url {
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error) {
[self handleError:error];
} else if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if (httpResponse.statusCode >= 400) {
NSError *httpError = [NSError errorWithDomain:@"HTTPErrorDomain" code:httpResponse.statusCode userInfo:nil];
[self handleError:httpError];
} else {
// 处理成功的响应
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"JSON: %@", json);
}
}
}];
[task resume];
}
- (void)handleError:(NSError *)error {
// 处理错误,例如显示错误消息给用户
NSLog(@"Error: %@", error);
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
NetworkClient *client = [[NetworkClient alloc] init];
NSURL *url = [NSURL URLWithString:@"https://example.com/api"];
[client sendRequestWithURL:url];
}
return 0;
}
在这个示例中,NSURLSessionDataTask
用于发送请求并在完成时处理响应。如果响应包含错误状态码,它会创建一个错误对象并调用handleError:
方法。
如果你在使用这些方法时仍然遇到问题,可能的原因包括:
解决这些问题的方法可能包括:
希望这些信息对你有所帮助。
领取专属 10元无门槛券
手把手带您无忧上云