最近、投稿に httpclient を使用すると、リモート インターフェイスでエラーが発生しました。
エラーメッセージ:
org.springframework.http.converter.HttpMessageNotReadableException: JSON 解析エラー: 認識できないトークン 'アラーム': 予期していました (JSON 文字列、数値、配列、オブジェクトまたはトークン 'null'、'true'、または 'false')。ネストされた例外は com.fasterxml.jackson.core.JsonParseException: 認識できないトークン 'アラーム': 予期していました (JSON 文字列、数値、配列、オブジェクトまたはトークン 'null'、'true'、または 'false')
理由と解決策:
理由は、リクエスト パラメータの形式が標準の json 形式ではなく正しくないためです。JSONObject オブジェクトを通じてパラメータを json 文字列に変換する、つまりメッセージ本文の構築コードを変更するだけです。
エラーコード:
public HttpEntity httpPost(String url, Alarm data){
try{
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建httpPost实例
HttpPost post = new HttpPost(url);
//构造消息头
post.setHeader("Content-type", "application/json; charset=utf-8");
// 构造消息体
StringEntity entity = new StringEntity(data.toString(), ContentType.create("application/json", "utf-8"));
post.setEntity(entity);
CloseableHttpResponse response = httpClient.execute(post);
HttpEntity responseEntity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
//最后关闭HttpClient资源.
httpClient.close();
return responseEntity;
}catch (Exception e){
e.printStackTrace();
return null;
}
}
変更されたコード:
public HttpEntity httpPost(String url, Alarm data){
try{
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建httpPost实例
HttpPost post = new HttpPost(url);
//构造消息头
post.setHeader("Content-type", "application/json; charset=utf-8");
// 构造消息体
StringEntity entity = new StringEntity(new JSONObject(data).toString(), ContentType.create("application/json", "utf-8"));
post.setEntity(entity);
CloseableHttpResponse response = httpClient.execute(post);
HttpEntity responseEntity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
//最后关闭HttpClient资源.
httpClient.close();
return responseEntity;
}catch (Exception e){
e.printStackTrace();
return null;
}
}
JSONObject は以下に依存します。
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20211205</version>
</dependency>