HttpUtil工具類,發送Get/Post請求,支持Http和Https協議


HttpUtil工具類,發送Get/Post請求,支持Http和Https協議

使用用Httpclient封裝的HttpUtil工具類,發送Get/Post請求

1. maven引入httpclient依賴

  <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.5.12</version>
  </dependency>

2. GET請求

public static String doGet(String path, Map<String, String> param, Map<String, String> headers) {
    HttpGet httpGet = null;
    CloseableHttpResponse response = null;
    CloseableHttpClient httpClient = wrapClient(path);
    // 創建uri
    URIBuilder builder = null;
    try {
        builder = new URIBuilder(path);
        if (param != null) {
            for (String key : param.keySet()) {
                builder.addParameter(key, param.get(key));
            }
        }
        URI uri = builder.build();
        // 創建http GET請求
        httpGet = new HttpGet(uri);
        if (headers != null && headers.size() > 0) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpGet.addHeader(entry.getKey(), entry.getValue());
            }
        }

        // 執行請求
        response = httpClient.execute(httpGet);
        // 判斷返回狀態是否為200
        if (response.getStatusLine().getStatusCode() == 200) {
            return EntityUtils.toString(response.getEntity(), "UTF-8");
        }
    } catch (Exception e) {
        throw new RuntimeException("[發送Get請求錯誤:]" + e.getMessage());
    } finally {
        try {
            httpGet.releaseConnection();
            response.close();
            if (httpClient != null) {
                httpClient.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

3. POST請求

public static String doPostJson(String url, String jsonParam, Map<String, String> headers) {
    HttpPost httpPost = null;
    CloseableHttpResponse response = null;
    CloseableHttpClient httpClient = wrapClient(url);
    try {
        httpPost = new HttpPost(url);
        //addHeader,如果Header沒有定義則添加,已定義則不變,setHeader會重新賦值
        httpPost.addHeader("Content-type","application/json;charset=utf-8");
        httpPost.setHeader("Accept", "application/json");
        StringEntity entity = new StringEntity(jsonParam, StandardCharsets.UTF_8);
//            entity.setContentType("text/json");
//            entity.setContentEncoding(new BasicHeader("Content-Type", "application/json;charset=UTF-8"));
        httpPost.setEntity(entity);
        //是否有header
        if (headers != null && headers.size() > 0) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpPost.addHeader(entry.getKey(), entry.getValue());
            }
        }
        // 執行請求
        response = httpClient.execute(httpPost);
        // 判斷返回狀態是否為200
        if (response.getStatusLine().getStatusCode() == 200) {
            return EntityUtils.toString(response.getEntity(), "UTF-8");
        }

    } catch (Exception e) {
        throw new RuntimeException("[發送POST請求錯誤:]" + e.getMessage());
    } finally {
        try {
            httpPost.releaseConnection();
            response.close();
            if (httpClient != null) {
                httpClient.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

3. 獲取httpclient的方法

這里會根據url自動匹配需要的是http的還是https的client

  private static CloseableHttpClient wrapClient(String url) {
      CloseableHttpClient client = HttpClientBuilder.create().build();
      if (url.startsWith("https")) {
          client = getCloseableHttpsClients();
      }
      return client;
  }

4. 對於https的需要自己實現一下client

private static CloseableHttpClient getCloseableHttpsClients() {
    // 采用繞過驗證的方式處理https請求
    SSLContext sslcontext = createIgnoreVerifySSL();
    // 設置協議http和https對應的處理socket鏈接工廠的對象
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", new SSLConnectionSocketFactory(sslcontext)).build();
    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    HttpClients.custom().setConnectionManager(connManager);
    // 創建自定義的httpsclient對象
    CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
    return client;
}
private static SSLContext createIgnoreVerifySSL() {
        // 創建套接字對象
        SSLContext sslContext = null;
        try {
            //指定TLS版本
            sslContext = SSLContext.getInstance("TLSv1.2");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("[創建套接字失敗:] " + e.getMessage());
        }
        // 實現X509TrustManager接口,用於繞過驗證
        X509TrustManager trustManager = new X509TrustManager() {
            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                                           String paramString) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                                           String paramString) throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        try {
            //初始化sslContext對象
            sslContext.init(null, new TrustManager[]{trustManager}, null);
        } catch (KeyManagementException e) {
            throw new RuntimeException("[初始化套接字失敗:] " + e.getMessage());
        }
        return sslContext;
    }

以上全部都測試通過,如果有錯誤,歡迎大佬們指出,感謝!!!

備注:完整版的點這里

讓堅持成為品質,讓優秀成為習慣!加油!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM