HttpClient如何采用JSON参数发送POST请求呢?
下文笔者讲述HttpClient向指定接口发送POST请求--并附加POST值
HttpClient发送POST请求
1.定义请求头为 application/json 2.将json信息放入到请求体中 3.使用HttpClient发送post请求例:httpClient发送POST请求的示例
public static JSONObject httpPost(String url, Map<String, String> params) { // post请求返回结果 CloseableHttpClient httpClient = HttpClientConfig.getHttpClient(); JSONObject jsonResult = null; HttpPost httpPost = new HttpPost(url); httpPost.setHeader("Content-type", "application/json; charset=utf-8"); try { if (null != params) { // 构建消息实体 Map转json字符串 StringEntity entity = new StringEntity(JSON.toJSONString(params), charset); entity.setContentEncoding("UTF-8"); // 发送Json格式的数据请求 entity.setContentType("application/json"); httpPost.setEntity(entity); } CloseableHttpResponse response = httpClient.execute(httpPost); return convertResponse(response); } catch (IOException e) { LOGGER.error("post请求提交失败:" + url, e); } finally { httpPost.releaseConnection(); } return jsonResult; } private static JSONObject convertResponse(CloseableHttpResponse response) throws IOException, ParseException { // 请求发送成功,并得到响应 JSONObject jsonObject = new JSONObject(); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // 读取服务器返回过来的json字符串数据 HttpEntity entity = response.getEntity(); String strResult = EntityUtils.toString(entity, charset); // 把json字符串转换成json对象 jsonObject = JSON.parseObject(strResult); } jsonObject.put("status",response.getStatusLine().getStatusCode()); return jsonObject; }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。