对于初入职场的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];
通过以上, 接下来就可以成功上传文件到服务器了.
网友评论
_manager = [[AFHTTPSessionManager alloc]init];
_manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/json", @"text/javascript", @"application/json", nil];
这一句里面,@"token-id"是固定的吗?