美文网首页日常收录
IOS AFNetWorking 通过body传递参数给服务器

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

作者: 谁拿浮生伴我一世流年 | 来源:发表于2017-10-31 13:28 被阅读157次

    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) {

    }];

    相关文章

      网友评论

        本文标题:IOS AFNetWorking 通过body传递参数给服务器

        本文链接:https://www.haomeiwen.com/subject/rykbpxtx.html