/**
* 发送HTTP请求 application/json
* @param url 请求地址
* @param json json请求参数
* @return HTTP响应
*/
public static String httpPost(String url, String json) {
// Http响应结果
String result = "";
// 创建HttpClientBuilder
HttpClientBuilder httpClientBuilder;
// HttpClient
CloseableHttpClient closeableHttpClient = null;
try {
httpClientBuilder = HttpClientBuilder.create();
closeableHttpClient = httpClientBuilder.build();
HttpPost httpPost = new HttpPost(url);
// 设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(10000)
.setConnectTimeout(10000).build();
httpPost.setConfig(requestConfig);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-Type", "application/json");
StringEntity stringEntity = new StringEntity(json,
Charset.forName("UTF-8"));
httpPost.setEntity(stringEntity);
CloseableHttpResponse response = closeableHttpClient
.execute(httpPost);
HttpEntity httpEntity = response.getEntity();
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
result = EntityUtils.toString(httpEntity, "UTF-8");
return result;
} else {
result = EntityUtils.toString(httpEntity, "UTF-8");
return result;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 释放资源
try {
closeableHttpClient.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
发送HTTP POST请求
于 2022-07-07 10:18:40 首次发布
博客涉及Java、HTTP和JSON相关信息技术内容,但具体内容缺失。Java是常用后端开发语言,HTTP是网络协议,JSON是数据交换格式,三者在信息技术领域应用广泛。
1715

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



