我们有一些代码在POST请求中发布图像和一些其他数据作为Multipart的一部分。在Android工作正常,但我似乎无法使其在iOS上工作,我不断得到500内部服务器错误。工作的Android代码看起来像
String uploadURL = "http://someServer.com/upload";
String imageToUploadPath = "imgFilePath";// path de la imagen a subir
String userId = "123";
String token = "abcd";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(uploadURL);
File f = new File(imageToUploadPath);
FileBody fileBody = new FileBody(f);
MultipartEntity reqEntity = new MultipartEntity();
Charset chars = Charset.forName("ISO-8859-1");
reqEntity.addPart("id", new StringBody(userId, chars));
reqEntity.addPart("token", new StringBody(token, chars));
reqEntity.addPart("image", fileBody);
httppost.setEntity(reqEntity);
HttpResponse response = httpClient.execute(httppost);
我的iOS尝试使用AFNetworking如下
uploadURLStr = @"http://someServer.com/upload";
NSString *token = @"abcd";
NSString *userID = @"123";
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSMutableSet *supportedContentTypes = [manager.responseSerializer.acceptableContentTypes mutableCopy];
supportedContentTypes addObject:@"text/html"];
manager.responseSerializer.acceptableContentTypes = supportedContentTypes;
NSURLSessionTask *task = [manager POST:uploadURLStr
parameters:nil
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
NSDictionary *tokenHeaders = @{@"Content-Disposition": @"form-data",
@"name": @"token",
@"Content-Type": @"text/plain",
@"charset": @"ISO-8859-1",
@"Content-Transfer-Encoding": @"8bit"
};
[formData appendPartWithHeaders:tokenHeaders body:[token dataUsingEncoding:NSISOLatin1StringEncoding]];
NSMutableDictionary *userIDHeaders = [tokenHeaders mutableCopy];
[userIDHeaders setObject:@"id" forKey:@"name"];
[formData appendPartWithHeaders:[userIDHeaders copy] body:[userID dataUsingEncoding:NSISOLatin1StringEncoding]];
NSDictionary *imgHeaders = @{@"Content-Disposition": @"form-data",
@"name": @"image",
@"filename": fileName,
@"Content-Type": @"application/octet-stream",
@"Content-Transfer-Encoding": @"binary"
};
[formData appendPartWithHeaders:imgHeaders
body:[imgData base64EncodedDataWithOptions:0]];
}
progress:^(NSProgress *uploadProgress) {
NSLog(@"progress: %.2f", uploadProgress.fractionCompleted);
}
success:^(NSURLSessionTask *task, id responseObject) {
NSLog(@"responseObject = %@", responseObject);
} failure:^(NSURLSessionTask *task, NSError *error) {
[self showUploadError];
NSLog(@"error = %@", error);
}];
我们设法从Android应用程序中记录每个部分的标题,以便我们复制它 - 例如,我发送的图像带有 Content-Type 的 image / jpeg 和Android将其作为 application / octet-stream 发送 - 我假设图像数据未按Android编码。我已尝试使用base64编码,因为它现在在代码中使用了除0-之外的其他选项,只是留下了由UIImageJPEG表示返回的NSData,但我无法敲响。任何帮助表示赞赏。