[英]Rest call with special characters giving "Event request must have valid JSON body" error in java
我正在尝试从 java 打一个休息电话。 在请求正文中,我有一个包含特殊字符的字段。 如果我从 java 执行这个 post 请求,那么它给我“事件请求必须具有有效的 JSON 正文”但是当我从邮递员执行相同的请求时,我得到 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);
有谁知道我需要对代码进行哪些更改才能解决此问题? 如果您需要其他信息,请告诉我。 提前致谢。
为了解决这个问题,我刚刚做了以下更改
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);
这看起来像是字符编码的问题。 您将setContentType
设置为application/json
但未设置最终默认为平台编码类型的字符编码。
为确保您将UTF-8
设置为处理此类特殊字符,请更改您的StringEntity
初始化,如下所示:
StringEntity input = new StringEntity(reqBody,ContentType.APPLICATION_JSON);
另外,删除input.setContentType("application/json");
调用,因为一旦使用上述构造函数就不需要它。 此构造函数将负责使用application/json
以及将编码设置为UTF-8
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.