之前发送请求传给后台的参数都是 NSDictionary 类型的,最近后台要求传参数是 json 类型。因此封装了一个postBody的方法。Post和postBody唯一的区别就是后台接受参数的类型不同,post默认是form表单提交,而postBody是在是吧jason放在HTTPBody中。
// 使用body传数据
+ (NSURLSessionTask *)postBodyWithApi:(NSString *)api json:(id)json callback:(APICallback)callback {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSMutableURLRequest *request = [manager.requestSerializer requestWithMethod:@"POST" URLString:urlstr parameters:nil error:&requestError];
request.timeoutInterval = 30;
// 设置header
[request setValue:@"" forHTTPHeaderField:@"token"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
// body
NSData *postData = [json dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:postData];
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request uploadProgress:^(NSProgress * _Nonnull uploadProgress) {
} downloadProgress:^(NSProgress * _Nonnull downloadProgress) {
} completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (!error) {
}else{
}
}];
[dataTask resume];
return dataTask;
}