封装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;
    }
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值