IOS AFNetWorking 通过body传递参数给服务器

post请求体封装如下:

- (void)postWithUrl:(NSString *)url body:(NSData *)body  success:(void(^)(NSDictionary *response))success failure:(void(^)(NSError *error))failur

{

NSString *requestUrl = @“”;

AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

//如果你不需要将通过body传 那就参数放入parameters里面

NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:requestUrl parameters:nil error:nil];

NSLog(@"requestURL:%@",requestUrl);

request.timeoutInterval= 10;

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

// 设置body 在这里将参数放入到body

[request setHTTPBody:body];

AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];

responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",

@"text/html",

@"text/json",

@"text/javascript",

@"text/plain",

nil];

manager.responseSerializer = responseSerializer;

[[manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse *response,id responseObject,NSError *error){

if(responseObject!=nil){

success(responseObject);

}

if (error) {

failure(error);

}

}]resume];

}


调用:

NSDictionary *dict = @{@"name":@"hello",@"sex":@"男"};

NSData *data =    [NSJSONSerialization dataWithJSONObject:dict options:NSUTF8StringEncoding error:nil];

[self postWithUrl:@"" body:data showLoading:0 success:^(NSDictionary *response) {

//NSString *result = [[NSString alloc] initWithData:response  encoding:NSUTF8StringEncoding];

NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:nil];  //解析

NSLog(@"%@",result);

} failure:^(NSError *error) {

}];

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容