CloseableHttpClient httpClient = HttpClients.createDefault();
try {
//创建一个获取连接客户端的工具
URIBuilder builder = new URIBuilder(url);
URI uri = builder.build();
//创建Post请求
HttpPost httpPost = new HttpPost(uri);
httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
//body请求参数
Map<String,Object> map = new HashMap<>();
map.put("","");
...
JSONObject jsonString = new JSONObject(map);
StringEntity entity = new StringEntity(jsonString.toString());
httpPost.setEntity(entity);
try {
CloseableHttpResponse response = httpClient.execute(httpPost);
org.apache.http.HttpEntity httpEntity = response.getEntity();
//请求状态码返回200则表示成功
if (response.getStatusLine().getStatusCode() == 200) {
JSONObject resultString = (JSONObject) JSONObject.parse(EntityUtils.toString(response.getEntity(), "UTF-8"));
return resultString;
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (URISyntaxException | UnsupportedEncodingException e) {
e.printStackTrace();
}
Java http(application/json)post请求方式代码示例
于 2023-02-21 15:37:32 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)