AFHTTPRequestOperationManager发布多部分请求不起作用

时间:2014-08-03 06:12:34

标签: objective-c ios7 afnetworking-2 blobstore afhttprequestoperation

以下是我在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);
}];

以下是我使用它的方式

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

无论出于何种原因,图像都已成功发布到服务器,但文本部分未成功发布。所以这是我的文字词典

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

例如,服务器一直抱怨phone为空。当我查看服务器日志时,textDictionary中没有任何数据进入服务器。

在有人说这是我的服务器之前:iOS不是唯一的客户端。所有其他客户端工作正常。无论出于何种原因,textDictionary都没有被发送。

我欢迎熟悉AFHTTPRequestOperationManager的人提供帮助。

这是错误日志

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> 

另外,试图阻止失败,我之前进行了编辑,但没有改变:我添加了

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

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

对于参考,这里是没有问题的等效安卓代码

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 个答案:

答案 0 :(得分:1)

我最终将所有字段,包括文本字段和图片放在constructingBodyWithBlock中。 (那里有其他一些东西,比如取消代码和自定义进度条,但你得到了一般的想法:)

       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];

在这里输入代码