我需要提出一个嵌套multipart数据中的请求。我需要以多零件形式数据发送图像,而其他详细信息也应在Multipart中。我的JSON请求如下:
{
"emailId": "vision.jav@avenger.com",
"phoneNumber": "7417385811",
"profileImage": "image",
"password": "12345678",
"customerDetails": {
"firstName": "vison",
"lastName": "vision"
},
"addressDetails": {
"city": "chicago",
"province": "NY",
"postalCode": "654987",
"latitude": "28.52",
"longitude": "77.54"
},
"userRole": {
"role": "CUSTOMER"
}
}
您必须创建一个像JSON结构这样的POJO类并设置所有值。
然后
@Multipart
@POST("uploadData.php")
Call<ServerResponse> uploadFile(@PartMap Map<String, RequestBody> map,@Part MultipartBody.Part file);
然后,您必须使用映射选项将数据发送到服务器。
Map<String, RequestBody> map = new HashMap<>();
map.put("PRODUCTID", RequestBody.create(MediaType.parse("text/plain"), ProductId));
MultipartBody.Part imageFile = null;
try {
File file = new File(Environment.getExternalStorageDirectory() + "/Download/Salty.png");
if file != null) {
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"),
file);
imageFile = MultipartBody.Part.createFormData("ImageFile", file.getName(), requestFile);
}
}
catch (Exception ex)
{
Log.d("UploadStatus", "Multipart Image as exception occurs");
}
ApiService uploadImage = ApiClient.getClient().create(ApiService.class);
Call<ServerResponse> fileUpload = uploadImage.uploadFile(map,imageFile);
fileUpload.enqueue(new Callback<ServerResponse>() {
@Override
public void onResponse(Call<ServerResponse> call, Response<ServerResponse> response) {
Toast.makeText(MainActivity.this, "Success " + response.message(), Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this, "Success " + response.body().toString(), Toast.LENGTH_LONG).show();
}
@Override
public void onFailure(Call<ServerResponse> call, Throwable t) {
Log.d("TAG", "Error " + t.getMessage());
}
});
供参考,我正在发布答案。我不知道如何在后端映射JSON对象。最后,我发现解决方案趋于多尝试。它为我工作。对于以上发布的请求,只需使用一个点(。(以及内部JSON对象即以下键。
- 要插入FirstName的数据,请使用" CustomerDetails.firstname"作为键。
- 类似地,用于姓氏" customerdetails.lastname"作为键。