Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

OkHttp – keep getting the error: "content-type of request should be application/json"

Why do I get this error "content-type of request should be application/json", because I encoded it application/json?
How to correct it?
In Postman the request is working fine.

int id = 208;
MediaType JsonType = MediaType.parse("application/json");
OkHttpClient client = new OkHttpClient();
String jsonBody = "{\"params\":[\"wandelnet\"," + id + "]}";
RequestBody body = RequestBody.create(jsonBody, JsonType);
Request request = new Request.Builder()
        .url( "https://wandelnet.api.routemaker.nl/routemaker/getPublishedRoute")
        .post(body)
        .addHeader("Content-Type", "application/json; charset=utf-8")
        .addHeader( "Accept", "application/json")
        .build();
Response response = client.newCall(request).execute();

The result is:

{"result":null,"error":{"code":"sherpaBadRequest","message":"content-type
of request should be application/json"}}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try creating the request body from bytes, not from a string:

RequestBody body = RequestBody.create(jsonBody.getBytes(“UTF-8”), JsonType);

OkHttp automatically adds a charset when it does string encoding, and we need to prevent this here.

You’ll also want to omit the Content-Type header in your request builder.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading