记录一下用httpUtil工具类的post请求带头部参数

本来网上有很多HttpUtil工具类封装,里面封装了各种doget/dopost

本身自己项目之前也有人用过,但是最近对接一个第三方短信平台,按照他们的文档需要传参头部参数,但是不知道为什么用现有的post请求没法修改头部参数,所以自己写一个post请求吧

            //短信平台要求固定的头部参数格式
Map header = Maps.newHashMap();
            header.put("Accept", "application/json;charset=utf-8");
            header.put("Content-Type", "application/json;charset=utf-8");
            //请求参数的账号密码以及加密
            LinkedHashMap map = new LinkedHashMap();
            map.put("userName", name);
            String result = HttpUtil.doPostJson("url", header, JsonHelper.objectToJson(map));

    public static String doPostJson(String url,Map headerMap, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            if (headerMap != null) {
                Iterator headerIterator = headerMap.entrySet().iterator();          //循环增加header
                while(headerIterator.hasNext()){
                    Entry elem = (Entry) headerIterator.next();
                    httpPost.addHeader(elem.getKey(),elem.getValue());
                }
            }
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "UTF8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

你可能感兴趣的:(开发随手记,http,网络协议,java)