我正在嘗試從 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);
有誰知道我需要對代碼進行哪些更改才能解決此問題?如果您需要其他資訊,請告訴我。提前致謝。
uj5u.com熱心網友回復:
為了解決這個問題,我剛剛做了以下更改
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);
uj5u.com熱心網友回復:
這看起來像是字符編碼的問題。您正在設定setContentType但未application/json設定最終默認為平臺編碼型別的字符編碼。
為確保您設定UTF-8為處理此類特殊字符,請使用以下更改StringEntity初始化:
StringEntity input = new StringEntity(reqBody,ContentType.APPLICATION_JSON);
另外,洗掉input.setContentType("application/json");呼叫,因為一旦使用上述建構式就不需要它。此建構式將負責使用application/json以及將編碼設定為UTF-8
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/478006.html
