http client工具类

http client工具类

	@UtilityClass
	@Slf4j
	public class HttpUtils {

    /**
     * 发送 get 请求
     *
     * @param url    接口地址
     * @param params 请求参数
     * @return
     */
    public static String doGet(String url, Map<String, String> headList, JSONObject params) {
        HttpGet httpGet = null;
        judgeTheUrl(url);
        try {
            httpGet = getHttpGet(params, url);
            return getResponse(httpGet, headList, null);
        } catch (Exception e) {
            e.printStackTrace();
            return "HTTP_ERROR" + e.toString();
        } finally {
            if (httpGet != null) {
                httpGet.releaseConnection();
            }
        }
    }

    /**
     * 发送 get 请求
     *
     * @param url    接口地址
     * @param params 请求参数
     * @return
     */
    public static String doGet2(String url, Map<String, String> headList, JSONObject params) throws IOException {
        HttpGet httpGet = null;
        judgeTheUrl(url);
        httpGet = getHttpGet(params, url);
        return getResponse(httpGet, headList, null);
    }
    
    /**
     * 发送 get 请求
     *
     * @param url    接口地址
     * @param params 请求参数
     * @return
     */
    public static String doGetHasTimeLimit(String url, Map<String, String> headList,
                                           JSONObject params, Integer timeout) throws IOException {
        HttpGet httpGet = null;
        judgeTheUrl(url);
        httpGet = getHttpGet(params, url);
        return getResponse(httpGet, headList, timeout);
    }

    /**
     * 发送post请求
     * url:访问的url
     * headList:头列表
     * params:json格式的请求参数
     */
    public static String doSoapPost(String url, Map<String, String> headList, String params) {
        HttpPost httpPost = null;
        judgeTheUrl(url);
        try {
            httpPost = getHttpPost(params, url);
            return getResponse(httpPost, headList, null);
        } catch (Exception e) {
            e.printStackTrace();
            return "HTTP_ERROR" + e.toString();
        } finally {
            if (httpPost != null) {
                httpPost.releaseConnection();
            }
        }
    }

/**
     * 获取httpPost
     *
     * @param params 请求参数
     * @param url    请求url
     * @return
     */
    private static HttpPost getHttpPost(String params, String url) {
        HttpPost httpPost;
        if (StringUtils.isNoneBlank(params)) {
            StringEntity stringEntity = new StringEntity(params, StandardCharsets.UTF_8);
            httpPost = new HttpPost(url);
            httpPost.setEntity(stringEntity);
        } else {
            httpPost = new HttpPost(url);
        }
        return httpPost;
    }

    /**
     * 发送get请求
     * url:访问的url
     * headList:头列表
     * params:json格式的请求参数
     */
    public static HttpContext doGetInputStream(String url, Map<String, String> headList, JSONObject params) {
        HttpGet httpGet;
        judgeTheUrl(url);
        try {
            httpGet = getHttpGet(params, url);
            return HttpContext.builder()
                    .inputStream(getInputStreamResponse(httpGet, headList))
                    .httpRequestBase(httpGet)
                    .build();
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }
    
	/**
     * 发送get请求
     * url:访问的url
     * headList:头列表
     * params:请求参数
     */
    public static HttpContext doGetInputStream(String url, Map<String, String> headList, List<String> params) {
        HttpGet httpGet;
        judgeTheUrl(url);
        try {
            httpGet = getHttpGet(params, url);
            HttpResponse httpResponse = getHttpResponse(httpGet, headList, null);
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity httpEntity = httpResponse.getEntity();
                return HttpContext.builder()
                        .inputStream(httpEntity.getContent())
                        .httpRequestBase(httpGet)
                        .responseHeaders(httpResponse.getHeaders("Content-disposition"))
                        .build();
            } else {
                log.error("获取响应异常");
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }

    /**
     * 发送post请求
     * url:访问的url
     * headList:头列表
     * params:json格式的请求参数
     */
    public static String doPost(String url, Map<String, String> headList, JSONObject params) {
        HttpPost httpPost = null;
        judgeTheUrl(url);
        try {
            httpPost = getHttpPost(params, url, true);
            return getResponse(httpPost, headList, null);
        } catch (Exception e) {
            e.printStackTrace();
            return "HTTP_ERROR" + e.toString();
        } finally {
            if (httpPost != null) {
                httpPost.releaseConnection();
            }
        }
    }
	
	/**
     * 发送post请求
     * url:访问的url
     * headList:头列表
     * params:json格式的请求参数
     */
    public static String doFormDataPost(String url, Map<String, String> headList, JSONObject params) {
        HttpPost httpPost = null;
        judgeTheUrl(url);
        try {
            httpPost = getHttpPost(params, url, false);
            return getResponse(httpPost, headList, null);
        } catch (Exception e) {
            e.printStackTrace();
            return "HTTP_ERROR" + e.toString();
        } finally {
            if (httpPost != null) {
                httpPost.releaseConnection();
            }
        }
    }

    /**
     * 发送post请求
     * url:访问的url
     * headList:头列表
     * params:json格式的请求参数
     */
    public static HttpContext doPostInputStream(String url, Map<String, String> headList, JSONObject params) {
        HttpPost httpPost;
        judgeTheUrl(url);
        try {
            httpPost = getHttpPost(params, url, true);
            return HttpContext.builder()
                    .inputStream(getInputStreamResponse(httpPost, headList))
                    .httpRequestBase(httpPost)
                    .build();
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }
	
	/**
     * 获取httpPost
     *
     * @param params 请求参数
     * @param url    请求url
     * @return
     * @throws IOException
     */
    private static HttpPost getHttpPost(JSONObject params, String url, Boolean jsonContent) {
        HttpPost httpPost;
        if (params != null && params.size() > 0) {
            if (jsonContent) {
                StringEntity stringEntity = new StringEntity(params.toString(), StandardCharsets.UTF_8);
                httpPost = new HttpPost(url);
                httpPost.setEntity(stringEntity);
            } else {
                httpPost = new HttpPost(url);
                try {
                    httpPost.setEntity(new UrlEncodedFormEntity(getNameValuePair(params)));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        } else {
            httpPost = new HttpPost(url);
        }
        return httpPost;
    }

    /**
     * 获取httpGet
     *
     * @param params 请求参数
     * @param url    请求url
     * @return
     * @throws IOException
     */
    private static HttpGet getHttpGet(JSONObject params, String url) throws IOException {
        HttpGet httpGet;
        List<NameValuePair> paramStr = getNameValuePair(params);
        if (paramStr != null && paramStr.size() > 0) {
            String str = EntityUtils.toString(new UrlEncodedFormEntity(paramStr, "UTF-8"));
            httpGet = new HttpGet(url + "?" + str);
        } else {
            httpGet = new HttpGet(url);
        }
        return httpGet;
    }

	/**
     * 获取httpGet
     *
     * @param params 请求参数
     * @param url    请求url
     * @return
     * @throws IOException
     */
    private static HttpGet getHttpGet(List<String> params, String url) throws IOException {
        HttpGet httpGet;
        if (params != null && params.size() > 0) {
            String paramStr = StringUtils.join(params, "/");
            httpGet = new HttpGet(url + "/" + paramStr);
        } else {
            httpGet = new HttpGet(url);
        }
        return httpGet;
    }

    /**
     * 获取响应输入流
     *
     * @param httpRequestBase 请求方式
     * @param headList        请求头
     * @return
     * @throws IOException
     */
    private static InputStream getInputStreamResponse(HttpRequestBase httpRequestBase, Map<String, String> headList) throws IOException {
        HttpResponse httpResponse = getHttpResponse(httpRequestBase, headList, null);
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity httpEntity = httpResponse.getEntity();
            return httpEntity.getContent();
        } else {
            log.error("获取响应异常");
            return null;
        }
    }

	/**
     * 获取HttpResponse
     *
     * @param httpRequestBase 请求方式
     * @param headList        请求头
     * @param timeout
     * @return
     * @throws IOException
     */
    private static HttpResponse getHttpResponse(HttpRequestBase httpRequestBase, Map<String, String> headList, Integer timeout) throws IOException {
        HttpClient httpClient = HttpClients.createDefault();
        httpRequestBase.setConfig(getRequestConfig(timeout));
        if (headList != null && headList.size() > 0) {
            headList.forEach(httpRequestBase::addHeader);
        }
        return httpClient.execute(httpRequestBase);
    }

    /**
     * 获取响应内容
     *
     * @param httpRequestBase 请求
     * @param headList        请求头
     * @param timeout
     * @return
     * @throws IOException
     */
    private static String getResponse(HttpRequestBase httpRequestBase, Map<String, String> headList, Integer timeout) throws IOException {
        HttpResponse httpResponse = getHttpResponse(httpRequestBase, headList, timeout);
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
            /*如果报异常返回异常 不返回空*/
            HttpEntity httpEntity = httpResponse.getEntity();
            return EntityUtils.toString(httpEntity);
        }
        HttpEntity httpEntity = httpResponse.getEntity();
        return EntityUtils.toString(httpEntity);
    }

	/**
     * 获取NameValuePair
     *
     * @param params json参数
     */
    private static List<NameValuePair> getNameValuePair(JSONObject params) {
        if (params == null) {
            return null;
        }
        List<NameValuePair> nameValuePairs = new LinkedList<>();
        params.forEach((k, v) -> nameValuePairs.add(new BasicNameValuePair(k, (String) v)));
        return nameValuePairs;
    }

    /**
     * 设置超时
     *
     * @param timeout
     */
    private static RequestConfig getRequestConfig(Integer timeout) {
        if (Objects.nonNull(timeout) && timeout <= 0) {
            throw new RuntimeException("时间不可小于0");
        }
        // 设置超时
        return RequestConfig.custom()
                .setConnectionRequestTimeout(Objects.isNull(timeout) ? 50000 : timeout)
                .setConnectTimeout(Objects.isNull(timeout) ? 50000 : timeout)
                .setSocketTimeout(Objects.isNull(timeout) ? 50000 : timeout).build();
    }

	/**
     * 判断参数
     *
     * @param url 请求url
     */
    private static void judgeTheUrl(String url) {
        if (StringUtils.isBlank(url)) {
            throw new BusinessException("发起请求的url不能为空,请输入");
        }
    }

    /**
     * http内部类
     */
    @Data
    @Builder
    public class HttpContext {
        /**
         * 输入流
         */
        private InputStream inputStream;
        /**
         * 请求方式
         */
        private HttpRequestBase httpRequestBase;

        private Header[] responseHeaders;
    }

}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值