- OC-GET請求方式代碼
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager GET:@"https://www.baidu.com/" parameters:nil headers:@{} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"成功----%@",[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"失敗----%@",error);
}];
會妥妥的報錯
Domain=com.alamofire.error.serialization.response
Code=-1016 "Request failed: unacceptable content-type: text/html"
UserInfo={NSLocalizedDescription=Request failed: unacceptable content-type: text/html, NSErrorFailingURLKey=https://www.baidu.com/, com.alamofire.serialization.response.error.data
百度錯誤會讓你添加一句這個代碼
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript"憔足,@"text/html", nil];
但是還會報其他錯誤
Domain=NSCocoaErrorDomain Code=3840
"JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
為了從根本上解決Code=-1016錯誤镜悉,并避免Code=3840 錯誤,其實只需要一行代碼:
// 添加這句代碼
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
GET實例代碼(POST請求方式同理):
- (void)get {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
// 添加這句代碼
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager GET:@"https://www.baidu.com/" parameters:nil headers:@{} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"成功----%@",[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"失敗----%@",error);
}];
}