前言
服务器因为框架不用、制定的接口协议不同所以AFN直接调用POST请求不能够满足需求,在这里特地来写记一下。
请求方式(表单提交)
contentType: application/x-www-form-urlencoded
服务器要求参数上传格式为reqMsg = {json}这样类型的参数放在body中,使用多文件的形式拼接在接口中
示例代码
//开始网络请求菊花
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
//初始化请求
NSString *baseUrl = [_dataSessionManager.baseURL absoluteString];
NSString *tmpStr = [baseUrl stringByAppendingFormat:TerminalAction,pathStr];
//设置urlStr
NSString *urlStr = [tmpStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//设置请求方式为POST
NSString *methodStr = [self stringWithMethod:method];
__block NSURLSessionDataTask *task = nil;
NSError * initRequestError;
NSString * token = [IdentityManager manager].identity.token;
//1.在此处创建requst,将reqMsg的json以多文件的形式拼接进去,key为reqMsg,value为参数json
NSMutableURLRequest * request = [[AFHTTPRequestSerializer serializer]multipartFormRequestWithMethod:methodStr URLString:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
//2.将参数字典转为jsonData拼接到formData中,name为reqMsg
NSLog(@"url:%@ parameters:%@ = %@ , %@ = %@",urlStr,REQMSG,((NSDictionary *)parameters).mj_JSONString, TOKEN, token);
[formData appendPartWithFormData:[((NSDictionary *)parameters).mj_JSONString dataUsingEncoding:NSUTF8StringEncoding] name:REQMSG];
} error:&initRequestError];
//3.判断错误
if (initRequestError) {
if (failureBlock) {
}
return nil;
}
//添加token
if (token) {
[request setValue:token forHTTPHeaderField:@"X-Auth-Token"];
}
//4.初始化网络请求。_uploadSessionManager为AFNSessionManager的对象
task = [_uploadSessionManager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
// 结束菊花
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}];
//5.发起请求任务,千万不要忘了这句话
[task resume];
在地址栏拼接参数
我们常用的方法是直接把参数字典放到AFN的parameters,这时候如果后台要求在地址栏拼接参数的话就尴尬了。我的做法是遍历parameters然后拼接到request的body中,完成请求
NSMutableArray * parameters = [NSMutableArray new];
//self.requestParameter为外部传进来的参数字典
//1.遍历字典
[self.requestParameter enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
//2.将参数字典按照key=value的形式存放到数组中
[parameters addObject:[NSString stringWithFormat:@"%@=%@", key, obj]];
}];
//3.创建request
NSMutableURLRequest * requst = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.urlString]];
//4.设置请求方式,默认为GET
requst.HTTPMethod = @"POST";
//5.将parameters按照&拼接起来并且放到HTTPBody中,注意:此处的parameters为可变数组,
requst.HTTPBody = [[parameters componentsJoinedByString:@"&"] dataUsingEncoding:NSUTF8StringEncoding];
//6.创建请求。self.session为AFNSessionManager的对象
self.dataTask = [self.session dataTaskWithRequest:requst completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
//to do ,请求返回
}];
//7.发起请求,千万不要忘了这句话
[self.dataTask resume];