记一个HttpClient创建Post请求,如何将Map参数转成StringEntity
public static JSONObject doPost(String url, Map<String, Object> params) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
HttpPost httpPost = new HttpPost(url);
// 设置请求头为JSON
httpPost.setHeader("Content-Type", "application/json");
// 将Map转换为JSON字符串
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(params);
// 设置请求体
httpPost.setEntity(new StringEntity(json, StandardCharsets.UTF_8));
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
HttpEntity responseEntity = response.getEntity();
if (responseEntity!= null) {
String result = EntityUtils.toString(responseEntity);
return JSON.parseObject(result);
}
} else {
throw new BusinessException("上传失败");
}
} finally {
response.close();
}
} catch (Exception e) {
throw e;
} finally {
httpClient.close();
}
throw new BusinessException("上传失败");
}
2290

被折叠的 条评论
为什么被折叠?



