我想用这个JSON主体(包含图片)和Retrofit做一个PUT请求。我在Android下使用它:
{
"Request": {
"data": {
"Key": "keydata",
"param": {
"title": "Testingpostmultipartimageupload",
"photo": **"IMAGE BYTE DATA"**
}
}
}
}
任何线索?
答案 0 :(得分:17)
好的,我找到了一个使用multipart的解决方案,像这样的事情:
@Multipart
@PUT("/users/{id}")
void modifyPic(
@Header("auth_token") String token,
@Path("id") int userid,
@Part("request[data][param][title]") String title,
@Part("request[data][param][Photo]") TypedFile avatar,
Callback<User> cb
);
答案 1 :(得分:0)
您需要使用多部分表单数据将图像数据放入字节中。
try {
HttpPost httppost = new HttpPost("some url");
MultipartEntity multipartEntity =
new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntity.addPart("Image", new FileBody(image));
httppost.setEntity(multipartEntity);
mHttpClient.execute(httppost, new YOURHANDLER());
} catch (Exception e) {
Log.e(ServerCommunication.class.getName(), e.getLocalizedMessage(), e);
}
使用参数
发送帖子请求HttpPost httpPost = new HttpPost(url);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
if (values != null) {
for (Map.Entry<String, String> entry : values.entrySet()) {
nameValuePairs.add(
new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
}
答案 2 :(得分:0)
Retrofit只需要multipart和requestbody作为其multipart。
Call<SubmitLevel1Part2IconResp> loadLevel1halfIconswithImage(@Part("headerdata[relation][icon_type]") RequestBody icon_type, @Part("headerdata[relation][name]") RequestBody name, @Part MultipartBody.Part file);
然后在java
// MultipartBody.Part is used to send also the actual filename
MultipartBody.Part body = MultipartBody.Part.createFormData("headerdata[relation][relative_image]", fileUpload.getName(), requestFile);
call = service.loadLevel1halfIconswithImage(icon_type, name, body);