body请求
- (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":@"小伙子",@"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) {
}];
网友评论