AFNetworking的請求頭設定(token)

weixin_33782386發表於2016-11-25

對於初入職場的iOS小夥伴們, 搭建UI--大家肯定是沒什麼問題了.

而對於網路請求的POST和GET, 應該還是會有問題;

例如, 如何將APP的token捆綁到請求中, 進行檔案的上傳 -- 現在我們就來解決下面兩個問題:

1,如何將token新增到請求頭?     2, 上傳失敗, 會出現的部分error解決.

問題一: 新增token到請求頭的程式碼如下:

NSDictionary *dict =  @{@"name" : @"小明",

@"age" :@"20"

};

//例項化AFHTTPSessionManager

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

//調出請求頭

manager.requestSerializer = [AFJSONRequestSerializer serializer];

//將token封裝入請求頭

[manager.requestSerializer setValue:TOKEN forHTTPHeaderField:@"token-id"];

//post上傳檔案

[manager POST:@"http://192.168.0.90/****" parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

NSLog(@"上傳成功 === %@",responseObject);

} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

NSLog(@"上傳錯誤 == error == %@",error);

}];


問題二: 上傳失敗, 有時候會出現如下error:

"error == Error Domain=com.alamofire.error.serialization.response Code=-1016 "Request failed: unacceptable content-type: text/plain" UserInfo={com.alamofire.serialization.response.error.response={ URL: http://192.168.0.192/api/grey/blood_pressure/upload_data } { status code: 200, headers {

Connection = "keep-alive";

"Content-Type" = "text/plain;charset=UTF-8";

Date = "Fri, 25 Nov 2016 01:05:46 GMT";

Server = "nginx/1.11.5";

"Transfer-Encoding" = Identity;

} }, NSErrorFailingURLKey=http://192.168.0.192/api/grey/blood_pressure/upload_data, com.alamofire.serialization.response.error.data=<7b227265 73756c74 5f636f64 65223a22 30222c22 72657375 6c745f6d 7367223a 22737563 63657373 227d>, NSLocalizedDescription=Request failed: unacceptable content-type: text/plain}"

請不要慌張, 只需要你在AFNetworking的第三方框架內找到AFURLResponseSerialization.m 檔案

修改第228行程式碼, 新增一項@"text/plain", 同時新增@"text/xml"也是在這個地方:

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

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

通過以上, 接下來就可以成功上傳檔案到伺服器了.

相關文章