I am completing this project that uses okhttp to communicate with webservice.
Everything works fine for regular GET and POST, but I can't load the file correctly.
The okhttp docs are sorely lacking on these topics, and everything I found here or somewhere doesn't seem to work in my case.
It should be simple: I have to send both the file and some string values. But I canβt figure out how to do this.
Following some patterns that I found, I tried this first:
RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM) .addFormDataPart("group", getGroup()) .addFormDataPart("type", getType()) .addFormDataPart("entity", Integer.toString(getEntity())) .addFormDataPart("reference", Integer.toString(getReference())) .addPart(Headers.of("Content-Disposition", "form-data; name=\"task_file\""), RequestBody.create(MediaType.parse("image/png"), getFile())) .build();
This gives me the error "400 bad request."
So, I tried this from okhttp recipes:
RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM) .addPart(Headers.of("Content-Disposition", "form-data; name=\"group\""), RequestBody.create(null, getGroup())) .addPart(Headers.of("Content-Disposition", "form-data; name=\"type\""), RequestBody.create(null, getType())) .addPart(Headers.of("Content-Disposition", "form-data; name=\"entity\""), RequestBody.create(null, Integer.toString(getEntity()))) .addPart(Headers.of("Content-Disposition", "form-data; name=\"reference\""), RequestBody.create(null, Integer.toString(getReference()))) .addPart(Headers.of("Content-Disposition", "form-data; name=\"task_file\""), RequestBody.create(MediaType.parse("image/png"), getFile())) .build();
The same result.
I donβt know what else to try or what to think in order to debug this.
The request is executed using this code:
// adds the required authentication token Request request = new Request.Builder().url(getURL()).addHeader("X-Auth-Token", getUser().getToken().toString()).post(requestBody).build(); Response response = client.newCall(request).execute();
But I'm sure the problem is how Im creates the request body.
What am I doing wrong?
EDIT: "getFile ()" above returns a File object, by the way. The remaining parameters are all strings and ints.