AFHTTPRequestOperationManager post multi-part request not working

被刻印的时光 ゝ 提交于 2019-11-28 10:32:44

问题


Here is the template that I am using from the Git Doc

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"foo": @"bar"};
[manager POST:@"http://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

Here is how I am using it

-(void)postMultipartToServer
{
    if (!self.destinationUrl) {
        return;
    }

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSLog(@"IS dictionary empty? %@", self.textDictionary);

    [manager POST:self.destinationUrl
       parameters:self.textDictionary
    constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        if ([self.imageDictionaries count]>0)
            for (NSDictionary *imgDic in self.imageDictionaries) {
                [formData appendPartWithFileData:UIImagePNGRepresentation([imgDic objectForKey:@"image"])
                                            name:[imgDic objectForKey:@"name"]//@"image"
                                        fileName:[imgDic objectForKey:@"fileName"]//@"image.png"
                                        mimeType:[imgDic objectForKey:@"mimeType"]//@"image/png"
                 ];
            }


    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"Success: %@", responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];
}

For whatever reason, the images are successfully posted to the server, but the text portions aren’t. So here is my text dictionary

 NSDictionary *textDictionary = @{
                                 @"userid”:self.userid,
                                 @"phone":self.phone,
                                 @"token”:self.userToken,
                                 @“age”:self.ageAsString,
                                 @“spouse”:self.spouse,
                                 @"isFamouse”:@”true"};

The server keeps complaining that phone is null, for example. When I look at the server logs, none of the data in textDictionary is making it to the server.

Before someone says it’s my server: iOS isn’t the only client. All the other clients work fine. For whatever reason, the textDictionary isn’t being sent.

I welcome any help from someone familiar with AFHTTPRequestOperationManager.

Here is the error log

Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: internal server error (500)" UserInfo=0x170477840 {com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x178225140> 

Also, trying to stop the failure, I made the edit before but no change: I added

AFSecurityPolicy *policy = [[AFSecurityPolicy alloc] init];
[policy setAllowInvalidCertificates:YES];

AFHTTPRequestOperationManager *operationManager = [AFHTTPRequestOperationManager manager];
[operationManager setSecurityPolicy:policy];
operationManager.requestSerializer = [AFJSONRequestSerializer serializer];
operationManager.responseSerializer = [AFJSONResponseSerializer serializer];

FOR REFERENCES HERE IS THE EQUIVALENT ANDROID CODE THAT IS WORKING WITHOUT A PROBLEM

public static void saveTextsAndImagesOnServer(List<byte[]> images, long someID1, String servingUrl, boolean someFlag)
        throws ClientProtocolException, IOException {
    Log.d(TAG, "saveTextsAndImagesOnServer started ");
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost postRequest = new HttpPost(servingUrl);
    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    AdditionData extr = AdditionData.getInstance();
    reqEntity.addPart("red", new ByteArrayBody(("" + extr.getred()).getBytes(), "red"));
    reqEntity.addPart("yellow", new ByteArrayBody(extr.getyellow.getBytes(), "yellow"));
    reqEntity.addPart("green", new ByteArrayBody(extr.getgreen().getBytes(), "green"));
    reqEntity.addPart("blue", new ByteArrayBody((extr.getblue()).getBytes(), "blue"));
    reqEntity.addPart("someID1", new ByteArrayBody(("" + someID1).getBytes(), "someID1"));
    if (someFlag) {
        reqEntity.addPart("someFlag", new ByteArrayBody("true".getBytes(), "someFlag"));
    }
    int i = 0;
    for (byte[] img : images) {
        ByteArrayBody image = new ByteArrayBody(img, "img" + i++ + ".png");
        reqEntity.addPart("image", image);
    }
    postRequest.setEntity(reqEntity);
    HttpResponse response = httpClient.execute(postRequest);
    Log.d(TAG, "saveTextsAndImagesOnServer ended with response " + response.toString());
}

回答1:


I ended up putting all fields, both text fields and images in the constructingBodyWithBlock. (There's some other stuff in there, like cancelling code and a custom progressbar, but you get the general idea :)

       NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer]
           multipartFormRequestWithMethod:@"POST"
                                URLString:self.destinationUrl
                               parameters:nil
                constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            [formData appendPartWithFormData:[self.userid dataUsingEncoding:NSUTF8StringEncoding] name:@"userid"];
            [formData appendPartWithFormData:[self.phone dataUsingEncoding:NSUTF8StringEncoding] name:@"phone"];

        // Add images as jpeg
        for (UIImage *image in images) {
            NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
            [formData appendPartWithFileData:imageData name:@"myFile" fileName:@"iphoneimage.jpg" mimeType:@"image/jpeg"];
        }

    } 
                                    error:nil];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
        NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
        if (!self.httpClientWasCancelled && !self.progressBar.isHidden) {
           [self.progressBar updateCurrentValue:totalBytesWritten/1024 andMax:totalBytesExpectedToWrite/1024];
        }
    }];

    [request setTimeoutInterval:1800];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *responseString = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"responseString = %@",responseString);
        [self.progressBar stopAndHide];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Request Error: %@", error);
        if (self.httpClientWasCancelled) {
            self.httpClientWasCancelled = NO;
        } else {
            [self.progressBar stopAndHide];
        }
    }];


    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
     [manager.operationQueue addOperation:operation];

enter code here



来源:https://stackoverflow.com/questions/25102155/afhttprequestoperationmanager-post-multi-part-request-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!