真实的国产乱ⅩXXX66竹夫人,五月香六月婷婷激情综合,亚洲日本VA一区二区三区,亚洲精品一区二区三区麻豆

成都創(chuàng)新互聯(lián)網(wǎng)站制作重慶分公司

Http、Https請求工具類-創(chuàng)新互聯(lián)

1. maven引入httpclient依賴
 ?org.apache.httpcomponents ? httpclient ?4.5.12
2. GET請求
public static String doGet(String path, Mapparam, Mapheaders) {
    HttpGet httpGet = null;
    CloseableHttpResponse response = null;
    CloseableHttpClient httpClient = wrapClient(path);
    // 創(chuàng)建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();
        // 創(chuàng)建http GET請求
        httpGet = new HttpGet(uri);
        if (headers != null && headers.size() >0) {
            for (Map.Entryentry : headers.entrySet()) {
                httpGet.addHeader(entry.getKey(), entry.getValue());
            }
        }

        // 執(zhí)行請求
        response = httpClient.execute(httpGet);
        // 判斷返回狀態(tài)是否為200
        if (response.getStatusLine().getStatusCode() == 200) {
            return EntityUtils.toString(response.getEntity(), "UTF-8");
        }
    } catch (Exception e) {
        throw new RuntimeException("[發(fā)送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, Mapheaders) {
    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.Entryentry : headers.entrySet()) {
                httpPost.addHeader(entry.getKey(), entry.getValue());
            }
        }
        // 執(zhí)行請求
        response = httpClient.execute(httpPost);
        // 判斷返回狀態(tài)是否為200
        if (response.getStatusLine().getStatusCode() == 200) {
            return EntityUtils.toString(response.getEntity(), "UTF-8");
        }

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

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

創(chuàng)新互聯(lián)于2013年開始,先為固陽等服務(wù)建站,固陽等地企業(yè),進(jìn)行企業(yè)商務(wù)咨詢服務(wù)。為固陽企業(yè)網(wǎng)站制作PC+手機+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問題。
private static CloseableHttpClient wrapClient(String url) {
      CloseableHttpClient client = HttpClientBuilder.create().build();
      if (url.startsWith("https")) {
          client = getCloseableHttpsClients();
      }
      return client;
  }
4. 對于https的需要自己實現(xiàn)一下client
private static CloseableHttpClient getCloseableHttpsClients() {
    // 采用繞過驗證的方式處理https請求
    SSLContext sslcontext = createIgnoreVerifySSL();
    // 設(shè)置協(xié)議http和https對應(yīng)的處理socket鏈接工廠的對象
    RegistrysocketFactoryRegistry = RegistryBuilder.create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", new SSLConnectionSocketFactory(sslcontext)).build();
    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    HttpClients.custom().setConnectionManager(connManager);
    // 創(chuàng)建自定義的httpsclient對象
    CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
    return client;
}
private static SSLContext createIgnoreVerifySSL() {
        // 創(chuàng)建套接字對象
        SSLContext sslContext = null;
        try {
            //指定TLS版本
            sslContext = SSLContext.getInstance("TLSv1.2");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("[創(chuàng)建套接字失敗:] " + e.getMessage());
        }
        // 實現(xiàn)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;
    }

你是否還在尋找穩(wěn)定的海外服務(wù)器提供商?創(chuàng)新互聯(lián)www.cdcxhl.cn海外機房具備T級流量清洗系統(tǒng)配攻擊溯源,準(zhǔn)確流量調(diào)度確保服務(wù)器高可用性,企業(yè)級服務(wù)器適合批量采購,新人活動首月15元起,快前往官網(wǎng)查看詳情吧


本文標(biāo)題:Http、Https請求工具類-創(chuàng)新互聯(lián)
本文網(wǎng)址:http://weahome.cn/article/hjcoe.html

其他資訊

在線咨詢

微信咨詢

電話咨詢

028-86922220(工作日)

18980820575(7×24)

提交需求

返回頂部