public static String HttpPostWithJson(String url, String json) {
String returnValue = "\"{\"msg\",\"传输失败未发送。\", \"success\": \"false\"}";
CloseableHttpClient httpClient = HttpClients.createDefault();
ResponseHandler<String> responseHandler = new BasicResponseHandler();
try {
// 第一步:创建HttpClient对象
httpClient = HttpClients.createDefault();
// 第二步:创建httpPost对象
HttpPost httpPost = new HttpPost(url);
// 第三步:给httpPost设置JSON格式的参数
StringEntity requestEntity = new StringEntity(json, "utf-8");
requestEntity.setContentEncoding("UTF-8");
httpPost.setHeader("Content-type", "application/json");
httpPost.setEntity(requestEntity);
// 第四步:发送HttpPost请求,获取返回值
returnValue = httpClient.execute(httpPost, responseHandler); // 调接口获取返回值时,必须用此方法
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 第五步:处理返回值
return returnValue;
}
post请求参数为json格式
最新推荐文章于 2025-10-01 20:33:05 发布
该代码示例展示了如何使用Java的HttpClient库执行一个HTTP POST请求,并发送JSON格式的数据。它创建了HttpClient对象,构造了一个HttpPost实例,设置了JSON参数,然后执行请求并处理返回值。
1万+

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



