I'm trying to make a rest call from java. In request body, I have one field which contains special characters. If I execute this post request from java then its giving me "Event request must have valid JSON body" but when I execute same request from postman then I'm getting 200ok response. Here is the request
{
"header": {
"headerVersion": 1,
"eventName": "add-incident",
"ownerId": "owner",
"appName": "abc",
"processNetworkId": "networkId",
"dataspace": "default"
},
"payload": {
"description": "Arvizturo tukorfurogepa€TM€¢ SchA1⁄4tzenstrasse a€¢",
"summary": "adding one issue"
}
}
This is how I'm executing request in java
String reqBody = "This is a json String cotaining same payload as above mentioned^^";
HttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(
RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build()
).build();
HttpPost postRequest = new HttpPost("Adding URL here");
StringEntity input = new StringEntity(reqBody);
input.setContentType("application/json);
postRequest.setEntity(input);
postRequest.addHeader("Authorization","Bearer " "Putting Authorisation Token Here");
HttpResponse response = httpClient.execute(postRequest);
Does anyone know what changes i need to do in code to resolve this issue? Let me know if you want other information. Thanks in advance.
CodePudding user response:
To resolve this I just made the below change
String finalBody = new String(reqBody.getBytes("UTF-8"),"UTF-8");
I set the encoding of the HTTP request string to UTF-8. This resolved my issue.
String reqBody = "This is a json String cotaining HTTP request payload";
String finalBody = new String(reqBody.getBytes("UTF-8"),"UTF-8");
HttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(
RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build()
).build();
HttpPost postRequest = new HttpPost("Adding URL here");
StringEntity input = new StringEntity(finalBody, ContentType.APPLICATION_JSON);
postRequest.setEntity(input);
postRequest.addHeader("Authorization","Bearer " "Putting Authorisation Token Here");
HttpResponse response = httpClient.execute(postRequest);
CodePudding user response:
This looks like issue with Character encoding. You are setting setContentType
to application/json
but not setting character encoding which eventually defaulted to platform encoding type.
To ensure you are setting UTF-8
to handle such special characters , change your StringEntity
initialization with below:
StringEntity input = new StringEntity(reqBody,ContentType.APPLICATION_JSON);
Also, remove input.setContentType("application/json");
call, as you don't need it once you use above mentioned constructor. This constructor will take care of using application/json
as well as setting encoding as UTF-8