当前位置:   article > 正文

封装http请求

封装http请求
    /**
     * 创建HTTPPOST请求
     *
     * @param url
     *            请求接口路径
     * @param headers
     *            待添加请求头内容
     * @param reqJsonStr
     *            请求的JSON字符串内容
     * @return
     */
    public static Result invoke(String url, Map<String, String> headers,
                                String reqJsonStr) throws IOException {
        // 创建httppost请求
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        Result result = new Result();
        try {
            HttpPost post = new HttpPost(url);// 请求方法地址
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(50000) // 设置连接超时时间
                    .setConnectionRequestTimeout(10000) // REQUEST超时时间
                    .setSocketTimeout(50000).build(); // 设置读取超时时间
            post.setConfig(requestConfig);
            StringEntity s = new StringEntity(reqJsonStr,
                    Charset.forName("UTF-8"));
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json; charset=utf-8");// 发送json数据需要设置contentType
            post.setEntity(s);
            post.setHeader("Accept", "application/json");
            if (headers != null) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    post.setHeader(entry.getKey(), entry.getValue());
                }
            }
            HttpResponse response = httpclient.execute(post);
            // 获取请求结果信息
            String content = EntityUtils.toString(response.getEntity());
            result.setObj(content);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// 200时表示成功
                result.setSuccess(true);
            } else {
                result.setSuccess(false);
                result.setMsg("HTTP请求发生错误,错误编码:"
                        + response.getStatusLine().getStatusCode());
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("请求异常,请联系管理员!");
            e.printStackTrace();
        } finally {
            httpclient.close();// 用完以后释放连接
        }
        return result;
    }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/210753?site
推荐阅读
相关标签
  

闽ICP备14008679号