Search code examples
javamultipartform-dataokhttp

Specify Content-Type in form-data part as application/json


I am creating a multipart RequestBody using OkHttp3. The following is the working curl request.

curl --location --request POST 'https://<url>' --form 'object=@<file_path>' --form 'config={"access":"YES"};type=application/json'

Removing ;type=application/json, produces an error from our Spring Boot server.

Content type 'application/octet-stream' not supported.

So it is clear that I should specify Json type for config. Let's create the Request using OkHttp.

String mimeType = URLConnection.getFileNameMap().getContentTypeFor(file.getName());
RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
            .addFormDataPart(
                "object", filename,
                RequestBody.create(MediaType.parse(mimeType), file)
            )
            .addFormDataPart("config", "{\"access\":\"YES\"}") // CAN'T FIND A WORKING OPTION TO SPECIFY CONTENT TYPE HERE.
            .build();

This produced the same error as mentioned above. So I changed the code as follows.

.addPart(
    Headers.of("Content-Type", "application/json"),
    RequestBody.create(MediaType.parse("application/json"), "{\"access\":\"YES\"}")
)

Now the OkHttp request builder throws this error.

Unexpected header: Content-Type

Using an empty header Headers.of(), creates the request body, but then I realized the form-data key config is not specified, from this API error.

Required request part 'config' is not present

I searched a lot, but can't find any solution with OkHttp, I found solutions in other libraries such as Spring RestTemplate.


Solution

  • This might work too.

    .addFormDataPart(
        "config",
        null,
        RequestBody.create(MediaType.parse("application/json"), "{\"access\":\"YES\"}")
    )