我正在使用HTTPS POST请求将照片上传到服务器。请求是Multipart,我使用此代码上传图片。
public HttpResponse uploadPhoto(File imagePath) {
try {
HttpPost httppost = new HttpPost(
"https://wbapi.cloudapp.net:443/api/Submission/UploadCompetitionEntry?folderName=photos");
MultipartEntity multipartEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
httppost.setHeader( "Content-Type", "multipart/form-data" );
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Authorization", getAuth());
multipartEntity.addPart("CompetitionID", new StringBody("84"));
multipartEntity.addPart("UserId", new StringBody(""
+ LoginActivity.id_user));
multipartEntity.addPart("Title", new StringBody(""
+ edit_title.getText().toString()));
multipartEntity.addPart("Summary", new StringBody(""
+ edit_description.getText().toString()));
multipartEntity.addPart("photos", new FileBody(imagePath,"image/jpeg"));
multipartEntity.addPart("MediaType", new StringBody("Photo"));
multipartEntity.addPart("Visibility", new StringBody("Public"));
multipartEntity.addPart("DateCreated", new StringBody(
"2013-01-04T10:07:46.9450000Z"));
httppost.setEntity(multipartEntity);
http = mHttpClient.execute(httppost);
} catch (Exception e) {
Log.v("Exception", "" + e.getMessage());
e.printStackTrace();
}
return http;
}
我的HTTPClient就是这个
mHttpClient = WinboutServerRequests.getHTTPClientObject();
这将使用Helper类来处理HTTPS证书。
当我正在执行请求时,我将e.getMessage()视为null并且在StackTrace中我得到了这个
我必须将这些实体发送到服务器
请求发送
curl -X POST“https://wbapi.cloudapp.net:443/api/Submission/UploadCompetitionEntry?folderName=photos”-F“摘要=我的描述”-F“CompetitionID = 84”-F“Title =照片标题“-F”MediaType =照片“-F”AuthorName = dog“-F”UserId = 1251“-F”DateCreated = 2013-01-04T10:07:46.9450000Z“-F”Visibility = Public“-F” photos = @ / Users / akshayhegde / Library / Application Support / iPhone Simulator / 5.1 / Applications / D8A03B97-B7CC-4655-8987-8A54AE3E5FFC / Documents / UserData / competitionEntry / photoEntryHeaderImage.jpg; type = application / octet-stream“
答案:
这个授权必须添加到缺少的标题中。我添加了它,现在我没有得到CientProtocolException。
添加了实用程序功能以获取文件的MIME类型
public static String getMimeType(String url)
{
String type = null;
String extension = MimeTypeMap.getFileExtensionFromUrl(url);
if (extension != null) {
MimeTypeMap mime = MimeTypeMap.getSingleton();
type = mime.getMimeTypeFromExtension(extension);
}
return type;
}
但是我收到415不支持的媒体类型错误,我们必须设置ContentType才能上传图片?
要发送的示例请求
内容 - 处置:表单数据; NAME = “CompetitionID”
内容 - 处置:表单数据; NAME = “用户ID”
内容 - 处置:表单数据; NAME = “标题”
内容 - 处置:表单数据;名称= “摘要”
内容 - 处置:表单数据; NAME = “的MediaType”
内容 - 处置:表单数据; NAME = “dateCreated会”
内容 - 处置:表单数据;名称= “可见性”
内容 - 处置:表单数据; NAME = “照片”;文件名= IMG_9322.JPG
内容 - 处置:表单数据; NAME = “视频”;文件名= SAMPLE.AVI
内容 - 处置:表单数据; NAME = “音乐”;文件名= SAMPLE.AVI
内容 - 处置:表单数据; NAME = “著作”;文件名= sample.txt的 内容类型:应用/八位字节流