问题
I need to make a request which is in nested multipart data. I need to send image in multi part form data and other details should also be in multipart. My Json request is as follow:
{
"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"
}
}
回答1:
You have to create one POJO class like your json structure and set all values.
then
@Multipart
@POST("uploadData.php")
Call<ServerResponse> uploadFile(@PartMap Map<String, RequestBody> map,@Part MultipartBody.Part file);
then You have to use mapping option to send data to the server.
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());
}
});
回答2:
For reference ,I am posting the answer. I don`t know how json object are being mapped at backend. Finally, I found the solution afer so many tries. Its working for me. For the above posted request , just use a dot(.) along with inner json object for making keys as Follows.
- For inserting data for firstName, Use "customerDetails.firstName" as key.
- similarly for last name use "customerDetails.lastName" as key .
来源:https://stackoverflow.com/questions/49973677/nested-multipart-request-using-retrofit