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 首次发布
该代码示例展示了如何在Java中利用ApacheHttpClient库创建一个POST请求,设置Content-Type为JSON,构建JSON对象,并处理HTTP响应。如果响应状态码为200,它将解析返回的JSON字符串。
post请求方式代码示例&spm=1001.2101.3001.5002&articleId=129143874&d=1&t=3&u=cd1e85f2e1a94b039f86fd5a8d4a1fff)
5904

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



