直接上代码

    public static String post(String url, String head, String body) throws Exception {

        // 创建httpClient的默认实例
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 忽略https证书验证
        httpClient = (CloseableHttpClient) wrapClient(httpClient);

        try {

            // 创建POST请求
            HttpPost post = new HttpPost(url);

            // 设置请求头
            post.addHeader("reqParameter", head);
            post.addHeader("Content-Type", "text/plain");

            // 设置请求体
            StringEntity entity = new StringEntity(body, "utf-8");
            post.setEntity(entity);

            // 执行POST请求
            CloseableHttpResponse response = httpClient.execute(post);
            if (response != null) {
                log.info("请求成功, 响应状态: {}", response.getStatusLine().getStatusCode());
                HttpEntity httpEntity = response.getEntity();
                // 如果返回的内容不为空
                if (httpEntity != null) {
                    return EntityUtils.toString(httpEntity, "UTF-8");
                }
            }

        } catch (Exception e) {
            log.error("请求异常: e = {}", e);
            e.printStackTrace();
        } finally {
            httpClient.close();
        }
        return null;
    }
    /**
     * description 忽略https证书验证
     *
     * @author yanzy
     * @version 1.0
     * @date 2021/9/8 14:42
     */
    public static HttpClient wrapClient(HttpClient base) {
        try {
            SSLContext ctx = SSLContext.getInstance("SSL");
            X509TrustManager tm = new X509TrustManager() {

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                @Override
                public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] arg0,
                                               String arg1) throws CertificateException {
                }
            };
            ctx.init(null, new TrustManager[]{tm}, null);
            SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);
            CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(ssf).build();
            return httpclient;
        } catch (Exception ex) {
            ex.printStackTrace();
            return HttpClients.createDefault();
        }
    }
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐