[英]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.