>>" + requestConfig.toString());//System.out.println("http请求信息>>>" + httpPost.toString());//System.out.println("请求数据转码>>>" + outEntity.toString());System.out.println("请求参数>>>" + message.toString());System.out.println("接口调用失败");">
当前位置:   article > 正文

http工具类

http工具类
public class HttpRequstUtil {

    /**
     * http请求方法
     *
     * @param message        查询条件
     * @param url            查询地址
     * @param token          身份验证token
     * @param socketTimeout  socket 响应时间
     * @param connectTimeout 超时时间
     * @return 返回字符串
     */
    @Deprecated
    public static String queryResultToString(JSON message, String url, String token, int socketTimeout, int connectTimeout) throws Exception {
        /*
        System.out.println("->开始http请求");
        System.out.println("请求参数>>>" + message.toString());
        System.out.println("请求链接>>>" + url);
        System.out.println("请求token>>>" + token);
        System.out.println("超时配置socketTimeout-connectTimeout>>>" + socketTimeout + "-" + connectTimeout);
         */
        String result = "";

        // 转码 将发送的数据转为字符串实体
        StringEntity outEntity = new StringEntity(message.toString(), "UTF-8");
        outEntity.setContentType("application/json");
        //System.out.println("请求数据转码>>>" + outEntity.toString());

        // 配置请求项
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();
        //System.out.println("请求配置项>>>" + requestConfig.toString());

        // 配置请求头
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", "application/json");
        httpPost.addHeader("Accept", "application/json");
        httpPost.addHeader("X-Aa-Token", token);
        httpPost.setEntity(outEntity);
        httpPost.setConfig(requestConfig);

        //System.out.println("http请求信息>>>" + httpPost.toString());
        try {
            result = (String) executeRequest(httpPost, true);
        } catch (Exception e) {
            throw new Exception(e.toString());
        }
        return result;
    }

    /**
     * @param httpRequest
     * @return java.lang.String
     * @description 执行Http请求
     * @date 2022/5/6 20:51
     */
    public static Object executeRequest(HttpUriRequest httpRequest, boolean isStr) throws IOException, DebtException, Exception {
        Object result = null;
        // 执行一个http请求,传递HttpGet或HttpPost参数
        CloseableHttpClient httpclient = null;
        if ("https".equals(httpRequest.getURI().getScheme())) {
            httpclient = createSSLInsecureClient();
        } else {
            httpclient = HttpClients.createDefault();
        }
        try {
            CloseableHttpResponse response = httpclient.execute(httpRequest);
            //判断接口是否调用成功
            int statusCode = response.getStatusLine().getStatusCode();
            if (HttpStatus.SC_OK != statusCode) {
                System.out.println("接口调用失败");
                throw new ApiException("接口调用失败,HttpStatus="+statusCode);
            } else {
                //System.out.println("发起请求->连接成功");
                HttpEntity entity = response.getEntity();
                // 是-获取字符串 否-获取字节数组
                if (isStr) {
                    result = EntityUtils.toString(entity, "UTF-8");
                } else {
                    result = EntityUtils.toByteArray(entity);
                }
                // 关闭资源
                EntityUtils.consume(entity);
            }
        } catch (Exception e) {
            throw new Exception(e.toString());
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                throw new IOException(e.toString());
            }
        }
        return result;
    }


    /**
     * 创建 SSL连接
     */
    private static CloseableHttpClient createSSLInsecureClient() throws Exception {
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            }).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (GeneralSecurityException ex) {
            throw new RuntimeException(ex);
        }
    }


    /**
     * @description 通过POST方式发送JSON数据
     * @author wangws
     * @date 2022/9/7 12:54
     * @param url     请求路径
     * @param message 待发送JSON信息
     * @param isStr   是否返回字符串(否,返回字节数组)
     * @param header  请求头Header(设置Token等)
     * @param timeOut 超时时间设置(socketTimeout,connectTimeout)
     * @return java.lang.Object
     */
    public static Object sendJsonByPost(String url, JSON message, boolean isStr, Map<String, String> header, Map<String, Integer> timeOut) throws Exception {
        Object result = null;
        // 1.创建http请求对象
        Object httpRequestObj = createHttpRequest("POST");
        if (!StringTool.isNull(httpRequestObj)) {
            HttpPost httpPost = (HttpPost) httpRequestObj;
            // 2.添加URL
            httpPost.setURI(URI.create(url));
            // 无需设置Header的Content-Type
            // 3.设置其他请求头信息
            if (!StringTool.isNull(header)) {
                Iterator<Map.Entry<String, String>> iterator = header.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry<String, String> next = iterator.next();
                    httpPost.addHeader(next.getKey(), next.getValue());
                }
            }
            // 添加JSON信息
            // 将发送的数据转为字符串实体
            StringEntity entity = new StringEntity(message.toString(), "UTF-8");
            entity.setContentType("application/json;charset=UTF-8");
            // 4.设置消息体
            httpPost.setEntity(entity);
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(timeOut.get("socketTimeout"))
                    .setConnectTimeout(timeOut.get("connectTimeout"))
                    .build();
            // 5.设置请求配置项
            httpPost.setConfig(requestConfig);
            // 6.执行Http请求对象,返回结果
            result = executeRequest(httpPost, isStr);
        } else {
            throw new ApiException("Http Request Method is not be matched");
        }
        return result;
    }
    /**
     * @param path    请求路径
     * @param message Get请求参数
     * @param isStr   是否返回字符串(否,返回字节数组)
     * @param header  请求头Header(设置Token等)
     * @param timeOut 超时时间设置(socketTimeout,connectTimeout)
     * @return java.lang.Object
     * @description 通过GET方式请求数据
     * @author wangws
     * @date 2022/10/18 12:54
     */
    public static Object sendDataByGet(String path, Map<String, String> message, boolean isStr, Map<String, String> header, Map<String, Integer> timeOut) throws Exception {
        Object result = null;
        // 1.创建http请求对象
        Object httpRequestObj = createHttpRequest("GET");
        if (!StringTool.isNull(httpRequestObj)) {
            HttpGet httpGet = (HttpGet) httpRequestObj;
            StringBuilder urlBuilder = new StringBuilder();
            // 设置接口地址
            urlBuilder.append(path);
            URIBuilder uri = new URIBuilder();
            // 设置网络协议
            //uri.setScheme("https");
            // 设置主机地址
            //uri.setHost("www.baidu.com");
            // 设置方法
            //uri.setPath("/getdata");
            //添加参数
            // 2.拼接GET请求参数
            if (!StringTool.isNull(message) && !message.isEmpty()) {
                Iterator<Map.Entry<String, String>> it = message.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry<String, String> next = it.next();
                    uri.setParameter(next.getKey(), next.getValue());
                }
            }
            urlBuilder.append(uri.build().toString());
            // 3.添加URL
            httpGet.setURI(new URI(urlBuilder.toString()));
            // 4.设置其他请求头信息
            if (!StringTool.isNull(header)) {
                Iterator<Map.Entry<String, String>> iterator = header.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry<String, String> next = iterator.next();
                    httpGet.addHeader(next.getKey(), next.getValue());
                }
            }
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(timeOut.get("socketTimeout"))
                    .setConnectTimeout(timeOut.get("connectTimeout"))
                    .build();
            // 5.设置请求配置项
            httpGet.setConfig(requestConfig);
            // 6.执行Http请求对象,返回结果
            result = executeRequest(httpGet, isStr);
        } else {
            throw new Exception("Http Request Method is not be matched");
        }
        return result;
    }
    /**
     * @description 通过POST方式上传文件
     * @author wangws
     * @date 2022/9/7 12:55
     * @param url     请求路径
     * @param file    待上传文件
     * @param isStr   是否返回字符串(否,返回字节数组)
     * @param header  请求头Header
     * @param param   待发送参数信息
     * @param timeOut 超时时间设置(socketTimeout,connectTimeout)
     * @return java.lang.Object
     */
    public static Object uploadFileByPost(String url, File file, boolean isStr, Map<String, String> header, Map<String, String> param, Map<String, Integer> timeOut) throws Exception {
        Object result = "";
        // 1.创建http请求对象
        Object httpRequestObj = createHttpRequest("POST");
        if (!StringTool.isNull(httpRequestObj)) {
            HttpPost httpPost = (HttpPost) httpRequestObj;
            // 2.添加URL
            httpPost.setURI(URI.create(url));
            // 3.追加文件(类似form表单),支持多个
            // RFC6532 避免文件名为中文时乱码
            MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
            // 参数名upload(可修改) 注意和后台接收时保持一致
            builder.addBinaryBody("upload", file, ContentType.MULTIPART_FORM_DATA, file.getName());
            builder.setCharset(Charset.forName("UTF-8"));
            // 无需设置Header的Content-Type,否则会出错
            // 4.设置其他请求头信息
            if (!StringTool.isNull(header)) {
                Iterator<Map.Entry<String, String>> iterator = header.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry<String, String> next = iterator.next();
                    httpPost.addHeader(next.getKey(), next.getValue());
                }
            }
            // 5.builder添加其他参数信息
            if (!StringTool.isNull(param)) {
                Iterator<Map.Entry<String, String>> it = param.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry<String, String> next = it.next();
                    builder.addTextBody(next.getKey(), next.getValue());
                }
            }
            HttpEntity entity = builder.build();
            // 6.设置消息体
            httpPost.setEntity(entity);
            // 7.设置配置项
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(timeOut.get("socketTimeout"))
                    .setConnectTimeout(timeOut.get("connectTimeout"))
                    .build();
            httpPost.setConfig(requestConfig);
            // 8.执行Http请求对象,返回JSON类型字符串
            result = executeRequest(httpPost, isStr);
        } else {
            throw new ApiException("Http Request Method is not be matched");
        }
        // 返回结果
        return result;
    }

    /**
     * @description 创建HttpRequest请求对象
     * @author wangws
     * @date 2022/9/7 12:55
     * @param requestMethod
     * @return java.lang.Object
     */
    public static Object createHttpRequest(String requestMethod) {
        // 大写转换
        requestMethod = requestMethod.toUpperCase();
        // 设置HTTP的请求方式
        if ("POST".equals(requestMethod)) {
            return new HttpPost();
        } else if ("GET".equals(requestMethod)) {
            return new HttpGet();
        } else if ("HEAD".equals(requestMethod)) {
            return new HttpHead();
        } else if ("PUT".equals(requestMethod)) {
            return new HttpPut();
        } else if ("PATCH".equals(requestMethod)) {
            return new HttpPatch();
        } else if ("DELETE".equals(requestMethod)) {
            return new HttpDelete();
        } else if ("OPTIONS".equals(requestMethod)) {
            return new HttpOptions();
        } else if ("TRACE".equals(requestMethod)) {
            return new HttpTrace();
        }
        return null;
    }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/184593
推荐阅读
相关标签
  

闽ICP备14008679号