本篇文章介绍了如何在Spring Boot项目中利用HttpClient库来实现发送POST请求的功能,并提供了详细的配置和代码示例。
public static String post(String url, String params) {
log.info(post url: + url + params: + params);
String responseStr = ;
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost(url);
StringEntity stringEntity = new StringEntity(params, Charset.forName(UTF-8));
httpPost.setHeader(Content-type, application/json);
httpPost.setEntity(stringEntity);
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
if (entity != null) {
responseStr = EntityUtils.toString(entity, Charset.forName(UTF-8));
}
} else {
log.error(Request failed with status code: + statusCode);
}
} finally {
response.close();
}
} catch (IOException e) {
log.error(Error occurred while executing the request, e);
}
return responseStr;
}