'Rest call with special characters giving "Event request must have valid JSON body" error in java

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.



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ashish Patil