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;
    }
相关推荐
运维Z叔1 小时前
云安全 | AWS S3存储桶安全设计缺陷分析
android·网络·网络协议·tcp/ip·安全·云计算·aws
weixin_456732591 小时前
网络-内核是如何与用户进程交互
网络·交互
陈大爷(有低保)2 小时前
UDP Socket聊天室(Java)
java·网络协议·udp
爱吃涮毛肚的肥肥(暂时吃不了版)2 小时前
计算机网络34——Windows内存管理
网络·计算机网络·udp
码哝小鱼3 小时前
firewalld封禁IP或IP段
linux·网络
sec0nd_3 小时前
1网络安全的基本概念
网络·安全·web安全
青柠视频云4 小时前
青柠视频云——视频丢包(卡顿、花屏、绿屏)排查
服务器·网络·音视频
网安CILLE4 小时前
2024年某大厂HW蓝队面试题分享
网络·安全·web安全
沐风ya4 小时前
Reactor介绍,如何从简易版本的epoll修改成Reactor模型(demo版本代码+详细介绍)
网络
SUGERBOOM4 小时前
【网络安全】网络基础第一阶段——第一节:网络协议基础---- OSI与TCP/IP协议
网络·网络协议·web安全