I am trying to send a POST request to a particular URL, below is my Java Code to do it...
OkHttpClient httpClient = new OkHttpClient().newBuilder().build();
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create("<JSON_AS_STRING>", JSON);
Request request = new Request.Builder()
.url(url)
.method("POST", body)
.addHeader("Authorization", getToken())
.addHeader("Content-Type", "application/json; charset=utf-8")
.build();
Response response = httpClient.newCall(request).execute()
When the request is excuted I am getting "Invalid content type" under error code 100. I am storing the JSON Body in a string and using it and defining media type to create a body.
But when I send same request from Postman, I am getting success code 204.
In Postman I have selected body as JSON and passing the JSON in the body and setting the URL and other headers like authorization and when I am sending the request I am getting 204.
But when I change it to text, then I get same error "Invalid content type" which I am getting from my Java code. I am using OkHttp3 library for client, request and response. How is my java code not taking media type as application/json. I even tried to pass "charset=utf-8" in header with application/json, still not working.
Any suggestions what could be going wrong, this is not the first time I am creating an okhttp3 request but first time seeing something like this...
Also I even tried to copy the java code snipped which you can create using postman...still not working.
I found the problem, when you set MediaType, then "charset=utf-8" was getting added which was leading to the error that I mentioned. So I removed the "charset=utf-8" manually and tried to send the request, this time I was using fiddler to listen to request sent from eclipse, turns out, whether you pass that charset or not, the MediaType will append it, so I tried to set the second parameter on MediaType.parse() as null, and just passed the header with Content Type as application/json, and it worked like a charm.