public String httpPostSession(String url, String jsonParam) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost method = new HttpPost(url);// post请求,非线程安全的
method.setHeader("Connection","close");// 必须设置
//method.setParams(HttpParam params);该方法在post请求中被标记弃用了
try {
if (null != jsonParam) {
StringEntity entity = new StringEntity(jsonParam, "UTF-8");//解决中文乱码问题
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
method.setEntity(entity);
}
HttpResponse result = httpClient.execute(method);
url = URLDecoder.decode(url, "UTF-8");
/**请求发送成功,并得到响应**/
if (result.getStatusLine().getStatusCode() == 200) {
try {
/**读取服务器返回过来的json字符串数据**/
resultStr = new String(EntityUtils.toString(result.getEntity()).getBytes("ISO8859-1"),"utf-8");
logger.info("返回信息:{}", resultStr);
} catch (Exception e) {
logger.info("post请求返回结果解析失败:{}", e.getMessage());
}
}
} catch (IOException e) {
logger.info("post请求提交失败:", e.getMessage());
}
return resultStr;
}
HttpClient的简单使用
最新推荐文章于 2023-12-06 10:31:57 发布
本文提供了一个使用 Java 发起 HTTP POST 请求的示例代码。该方法通过 HttpClient 库实现,可以传递 JSON 参数并接收服务器返回的 UTF-8 编码的 JSON 响应。
7018

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



