美文网首页
iOS AFNetWorking 通过body传参数

iOS AFNetWorking 通过body传参数

作者: 倒着游的鱼 | 来源:发表于2023-06-15 09:55 被阅读0次

    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) {
    
    }];
    

    相关文章

      网友评论

          本文标题:iOS AFNetWorking 通过body传参数

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