AFHTTPSessionManager add body to POST

后端 未结 2 1070
走了就别回头了
走了就别回头了 2021-02-08 04:43

I need too make a post request to my server.

With AFHTTPRequestOperation is very simple just use:

[request setHTTPBody: [requestBody dat         


        
2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-08 05:23

    Try this other way.

    I'm converting my image in data format which is imageData.

    NSData *imageData=nil;
    imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"yourimageName"],0.2);
    NSMutableDictionary *dict=[NSMutableDictionary new];
    [dict setObject:@"user1" forKey:@"param_name1"];
    [dict setObject:@"User2" forKey:@"param_name2"];
    
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] init];
    
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
    manager.responseSerializer = [AFJSONResponseSerializer
                                  serializerWithReadingOptions:NSJSONReadingAllowFragments];
    [manager POST:@"API NAME" parameters:dict constructingBodyWithBlock:^(id  _Nonnull formData) {
    
     if(imageData)
     {
         [formData appendPartWithFileData:imageData  name:@"param_name" fileName:@"filename.jpg" mimeType:@"image/jpeg"];
     }
     } progress:^(NSProgress * _Nonnull uploadProgress)
     {
         NSLog(@"%@",uploadProgress);
     } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
         NSLog(@"%@",responseObject);
    
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         NSLog(@"%@",error);
    
     }];
    

提交回复
热议问题