AFNetworking 遇到錯誤 Code=-1016 "Request failed: unacceptable content-type: text/plain"


在開發過程使用了AFNetworking庫,版本2.x,先運行第一個官方例子(替換GET 后面的url即可):

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:@"http://example.com/resources.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"JSON: %@", responseObject); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"Error: %@", error); }];
提示Error,但其實返回的是200 OK。
Error: Error Domain=com.alamofire.error.serialization.response Code=-1016 "Request failed: unacceptable content-type: text/plain"
UserInfo={com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x100438a90>
{ URL: http://testadmin.test.com/webservice/test } { status code: 200, headers {
    Connection = "Keep-Alive";
    "Content-Encoding" = gzip;
    "Content-Length" = 61;
    "Content-Type" = "text/plain";
    Date = "Mon, 22 Feb 2016 09:19:32 GMT";
    "Keep-Alive" = "timeout=10, max=10000";
    Server = "SNMW1.0";
    Vary = "Accept-Encoding";
} }, NSErrorFailingURLKey=http://testadmin.test.com/webservice/test,

經過查資料,是默認的AFNetworking庫,不支持解析 text/plain 類型,需要簡單修改源代碼就可以。
打開AFURLResponseSerialization.m,找到類 AFJSONResponseSerializer,修改它的init函數:
原內容:
- (instancetype)init {
    self = [super init];
    if (!self) {
        return nil;
    }

    self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil];
    return self;
}

修改為:
- (instancetype)init {
    self = [super init];
    if (!self) {
        return nil;
    }

    self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/javascript",@"text/plain", nil];
    return self;
}

其實就是增加了text/plain,就可以了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM