Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

objective c - AFHTTPRequestOperationManager post multi-part request not working

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());
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...