HTTP 406 錯誤指無法接受 (Not acceptable)錯誤。
如果Web伺服器檢測到其想要回報的資料不能被用戶端接受,其将回報帶有406錯誤代碼的标頭。 用戶端可以向Web伺服器訓示其将接受伺服器回報資料的特征,這是通過使用以下類型的“接受标頭”完成的:
接受:用戶端接受的MIME(多功能Internet郵件擴充服務)類型。 例如,浏覽器可能隻接受知道如何處理的回報資料類型(HTML檔案,GIF檔案等)。
1、原始的代碼:
public static String requestPost(String url, JSONObject params) {
//CloseableHttpClient httpClient = HttpClients.createDefault();
String responseResult = "";
try {
HttpClient httpClient = HttpsClient.getInstance();
// 1 建立一個post對象
HttpPost post = new HttpPost(url);
post.addHeader("Content-type", "application/json; charset=utf-8");
post.setHeader("Accept", "application/json");
// 2 建立一個Entity。模拟一個xml
log.info("HttpsClient.requestPost.params-->>" + params);
StringEntity stringEntity = new StringEntity(params.toJSONString(), "UTF-8");
stringEntity.setContentEncoding("UTF-8");
post.setEntity(stringEntity);
// 3 執行post請求
HttpResponse response = httpClient.execute(post);
//CloseableHttpResponse response = httpClient.execute(post);
HttpEntity he = response.getEntity();
responseResult = EntityUtils.toString(he, "UTF-8");
log.info("HttpsClient.requestPost.responseResult-->>" + responseResult);
//response.close();
//httpClient.close();
} catch (Exception e) {
e.printStackTrace();
log.info("HttpsClient.requestPost.Exception-->>" + e.getMessage());
}
return responseResult;
}
2、注解掉報錯的代碼
public static String requestPost(String url, JSONObject params) {
//CloseableHttpClient httpClient = HttpClients.createDefault();
String responseResult = "";
try {
HttpClient httpClient = HttpsClient.getInstance();
// 1 建立一個post對象
HttpPost post = new HttpPost(url);
post.addHeader("Content-type", "application/json; charset=utf-8");
//post.setHeader("Accept", "application/json");
// 2 建立一個Entity。模拟一個xml
log.info("HttpsClient.requestPost.params-->>" + params);
StringEntity stringEntity = new StringEntity(params.toJSONString(), "UTF-8");
stringEntity.setContentEncoding("UTF-8");
post.setEntity(stringEntity);
// 3 執行post請求
HttpResponse response = httpClient.execute(post);
//CloseableHttpResponse response = httpClient.execute(post);
HttpEntity he = response.getEntity();
responseResult = EntityUtils.toString(he, "UTF-8");
log.info("HttpsClient.requestPost.responseResult-->>" + responseResult);
//response.close();
//httpClient.close();
} catch (Exception e) {
e.printStackTrace();
log.info("HttpsClient.requestPost.Exception-->>" + e.getMessage());
}
return responseResult;
}
3、解決方案
注解掉://post.setHeader("Accept", "application/json")