HTTP请求工具类

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.11</version>
        </dependency>

引入以上pom文件。

@Slf4j
@Service
public class HttpFactory {
    /**
     * 通用方法
     *
     * @param reqUrl 用于组成http的发送的url
     * @param header 用于设置http的相关header的部分
     * @return JSONObject    返回viid的交互信息或者错误信息
     */
public static JSONObject sendGet(String reqUrl, Header header) {
/** 创建httpGet远程连接实例 **/
        HttpGet httpGet = new HttpGet(reqUrl);

        /** 设置请求头信息 **/
        if (null != header) {
            httpGet.addHeader(header);
        }

        /** 设置请求配置信息 **/
        RequestConfig requestConfig = setRequestConfig();
        httpGet.setConfig(requestConfig);

        return executeMethod(httpGet);
    }

public static JSONObject sendPost(String reqUrl, Header header, JSONObject jsonObject) {
        /** 创建httpPost远程连接实例 **/
        HttpPost httpPost = new HttpPost(reqUrl);

        /** 设置请求配置信息 **/
        RequestConfig requestConfig = setRequestConfig();
        httpPost.setConfig(requestConfig);
        if (null != header) {
            httpPost.addHeader(header);
        }
        httpPost.addHeader("Content-Type", "application/json");
                /** 设置消息体信息 **/
        StringEntity entity;
        if (null != jsonObject) {
            /** 解决参数中文乱码-所有信息编码使用UTF-8 **/
            entity = new StringEntity(jsonObject.toString(), "UTF-8");
        } else {
            entity = new StringEntity("", "UTF-8");
}

        entity.setContentEncoding("UTF-8");//设置编码格式
        entity.setContentType("application/json");
        httpPost.setEntity(entity);

        return executeMethod(httpPost);
}

    /**
     * 设置配置请求参数 时间都是毫秒级
     *
     * @return 配置类试下
     */
    private static RequestConfig setRequestConfig() {
        return RequestConfig.custom()
                .setConnectionRequestTimeout(10000).setConnectTimeout(10000)
     .setSocketTimeout(10000).build();
}
 /**
     * 执行http的请求-返回结果是json的请求
     *
     * @param httpRequestBase 请求基类
     * @return 处理结果
     */

private static JSONObject executeMethod(HttpRequestBase httpRequestBase) {


        /** http客户端 **/
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;

        /** 返回结果 **/
        String result;
        JSONObject jsonObject;
try {
            response = httpClient.execute(httpRequestBase);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity, "UTF-8");
            if (result.equals("[]")) {
                jsonObject = new JSONObject();
            } else {
                jsonObject = JSONObject.parseObject(result);
            }

 } catch (Exception e) {
            log.error("HttpClient request error:{}.", e.toString());
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("code", 1006);
            return jsonObject1;
        } finally {
            /** 关闭申请的资源 **/
            if (null != response) {
                try {
                    response.close();
                } catch (IOException e) {
                    /** 记录http关闭过程的异常 仅记录 不要影响处理结果 **/
             log.error("close response error:{}.", e.toString());
                }
            }

            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                 /** 记录http关闭过程的异常 仅记录 不要影响处理结果 **/
                    log.error("httpclient close error:{}.", e.toString());
                }
            }
        }

        return jsonObject;
    }

    /**
     * 如果你需要发送https请求并跳过ssl证书验证,请使用此方法
     * 条件:请求体格式为json
     *
     * @param url
     * @param body
     * @return
     */
public static String sendPostByHttps(String url, Map<String, String> body, String token) {
   CloseableHttpResponse response = null;
        // 处理请求路径
        url = UriComponentsBuilder.fromHttpUrl(url)
                .toUriString();
        //创建httpclient对象
        CloseableHttpClient client = null;
        String respBody;
  try {
            client = HttpClients.custom().setSSLSocketFactory(new SSLConnectionSocketFactory(SSLContexts.custom()
                            //忽略掉对服务器端证书的校验
                            .loadTrustMaterial(null, new TrustSelfSignedStrategy())
                            .build(),  NoopHostnameVerifier.INSTANCE))
                    .build();
            HttpPost httpPost = new HttpPost(url);
 // 请求头设置
            httpPost.setHeader("Accept", "*/*");
            httpPost.setHeader("connection", "Keep-Alive");
            httpPost.setHeader("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            httpPost.setHeader("Content-type", "application/json;charset=utf-8");
            httpPost.setHeader("Authorization", token);//如果需要token请修改传入自己的token以及Authorization
 if (body != null) {
                httpPost.setEntity(new StringEntity(JSON.toJSONString(body), "utf-8"));
            }
            //执行请求操作,并拿到结果
            response = client.execute(httpPost);
            //获取结果实体
            HttpEntity entity = response.getEntity();
 if (entity != null) {
                respBody = EntityUtils.toString(entity);
                return respBody;
            }
 } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
try {
                if (client != null) {
                    client.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                  }
        }

        return null;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值