带有特殊字符的 Rest 调用在 java 中给出 "Event request must have valid JSON body" 错误

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

我正在尝试从 java 拨打休息电话。在请求正文中,我有一个包含特殊字符的字段。如果我从 java 执行此 post 请求,那么它会给我 "Event request must have valid JSON body" 但是当我从post伙计,然后我收到了 200ok 的回复。 这是请求

{
"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"

}
}

这就是我在 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);

有谁知道我需要对代码进行哪些更改才能解决此问题? 如果您需要其他信息,请告诉我。 提前致谢。

这看起来像是字符编码问题。您将 setContentType 设置为 application/json 但未设置最终默认为平台编码类型的字符编码。

为确保您设置 UTF-8 来处理此类特殊字符,请将 StringEntity 初始化更改为以下内容:

StringEntity input = new StringEntity(reqBody,ContentType.APPLICATION_JSON);

此外,删除 input.setContentType("application/json"); 调用,因为一旦使用上述构造函数就不再需要它。此构造函数将负责使用 application/json 以及将编码设置为 UTF-8

为了解决这个问题,我做了以下更改

String finalBody = new String(reqBody.getBytes("UTF-8"),"UTF-8");

我将HTTP请求字符串的编码设置为UTF-8。这解决了我的问题。

    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);