我正在尝试使用相机运行时拍摄的一张图像发布JSONObject
。
如何在android中使用retrofit发布图像。
这是我的界面
@Multipart
@POST("/upload")
Call<Response> getDetails(@Part("empsno") String empsno,
@Part("time")String deliveryTime,
@Part("uploadFile") MultipartBody.Part part,
@Part("remarks")String remarks,
@Part("receiver")String receivedBy,
@Part("Address")String ipAddress
);
以前用上传图片及其他详细信息的代码
JSONObject oJSONObject = new JSONObject();
oJSONObject.put("empsno", strEmpsno);
oJSONObject.put("time", strtime);
oJSONObject.put("remarks", strRemarks);
oJSONObject.put("receiver", strReceiver);
oJSONObject.put("Address", straddress);
oJSONObject.put("uploadFile", imageFolderPath + "/" + imageName);
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("uploadFile", file.getName(), requestFile);
xInterface interface = retrofit.create(xInterface.class);
Call<Response> podResponsecall = interface.getDetails(strEmpsno, strtime,
body, strRemarks, strReceiver, straddress);
podResponsecall.enqueue(new Callback<Response>() {
@Override
public void onResponse(Response<Response> response) {
String val = response.body() + "";
Log.e(TAG, "onResponse: " + val);
}
@Override
public void onFailure(Throwable t) {
Log.e(TAG, "onFailure: " + t.getLocalizedMessage());
}
});
输出 - onFailure:JSON必须以数组或对象开头。
我不知道天气这是对还是错。请帮我用Retrofit2 beta 3发布一些图片以及其他细节。
答案 0 :(得分:2)
Service.class:
@Multipart
@POST("upload")
Call<Void> upload(@Part("model") RequestBody model, @Part MultipartBody.Part file);
改造2部分:
Gson gson = new GsonBuilder().setLenient().create();
RequestBody modelBody = RequestBody.create(MediaType.parse("application/json"), gson.toJson(modelPojo));
RequestBody reqFileBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part mPart1 = MultipartBody.Part.createFormData("file","name",reqFileBody);
Java Spring:
@PostMapping(value="/upload" ,consumes = {"multipart/form-data","application/json"})
public ResponseEntity<Object> uploadImagebyEmail(@RequestPart("model") Object model,@RequestPart("file") MultipartFile uploadfile ) throws IOException {
return //codes here...
}
答案 1 :(得分:0)
替换
@Multipart
@POST("/upload")
Call<ResponseBody> getDetails(@Part("empsno") RequestBody empsno,
@Part("time")RequestBody deliveryTime,
@Part("uploadFile") MultipartBody.Part part,
@Part("remarks")RequestBody remarks,
@Part("receiver")RequestBody receivedBy,
@Part("Address")RequestBody ipAddress
);
还有
Call<ResponseBody> podResponsecall = interface.getDetails(strEmpsno, strtime,
body, strRemarks, strReceiver, straddress);