HttpClient忽略SSL證書


今天公司項目請求一個接口地址是ip格式的,如:https://120.20.xx.xxx/xx/xx,報一個SSL的錯:

 

由於之前請求的接口地址都是域名地址,如:https://www.xxx.com/xxx/xxx,

 

借鑒博客:https://blog.csdn.net/qq173684423/article/details/53420695

 

使用HttpClient工具,忽略SSL認證代碼如下:

package com.saoptest.dhl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.xml.bind.DatatypeConverter;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.StatusLine;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;


/**
 * 
 * @Description: 測試歐洲國家DHL接口
 * @author: xxxx
 * @date: 2019年10月28日下午2:48:21
 */
public class DhlTest04EU {
    
    //測試歐洲國家DHL接口
    
    private static int socketTimeout = 300000;// 請求超時時間
    private static int connectTimeout = 300000;// 傳輸超時時間
    
    
    
    public static void main(String[] args) throws Exception  {
        
        
        
        String url = ""; //請求地址
        
        
        try{
            

            
            
            
            
            
            
            
            //==========1、發送get請求獲取token
//            url = "xxxxxx"; //請求地址
            url = "http://xxxxx"; //請求地址
            
//            String resultStr = doGetHttpClient(url); 
            String resultStr = testGetNoSSL(url); //get請求(忽略SSL證書),獲取結果
            
            JSONObject jsonObj = JSONObject.parseObject(resultStr);
            String accessToken = jsonObj.getString("access_token");
            System.out.println("拿到token:" + accessToken);
            
            
            //==========2、拿到token后,發送token和訂單參數
            url = "https://xxxxxxx";
            
            
            //獲取這個類的路徑path,參數有幾十個字段,所以測試寫死的放入文件里了
//            String path = "E:/dhl04.txt";
            String path = "E:/dhl05Str.txt";
            
            
             
            //path + "struts.xml",就是類路徑下的struts.xml這個文件了
            BufferedReader br = new BufferedReader(new FileReader(new File(path)));
            String s = "";
            String param = "";
             
            //定義一個變量s,讓s等於br去讀一行。
            while((s = br.readLine()) != null){
                //System.out.println(s);
                param += s;
            }
            System.out.println("========請求參數========================");
            System.out.println(param);
            
            String resultXml = testPostNoSSL(url, param, accessToken);
            System.out.println("\n返回結果:\n" + resultXml);
            
            
        } catch(Exception ee){
            
            System.out.println("錯誤===========" + ee);
        }
        
        
        
    }
    
    
    
    
    
    /**
     * 使用SOAP1.2發送消息
     * 
     * @param postUrl
     * @param soapXml
     * @param soapAction
     * @return
     */
    public static String doPostSoap1_3(String postUrl, String soapXml,String token) {


        String retStr = "";
        
        try {
            
//            CredentialsProvider provider = new BasicCredentialsProvider();
//            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("ectms", "Zoot123!");
//            provider.setCredentials(AuthScope.ANY, credentials);
//            //創建HttpClientBuilder
//            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().setDefaultCredentialsProvider(provider);
//            
//            
//            
//            
//            // HttpClient
//            CloseableHttpClient httpclient = httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy()).build();
//            CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
//            1、創建httpClient
            CloseableHttpClient httpclient = HttpClients.createDefault();
            
            
            HttpPost httpPost = new HttpPost(postUrl);
      
        //頭部添加token
            httpPost.setHeader("Authorization", "Bearer " +token);
            
            
            
            // 設置請求和傳輸超時時間
            RequestConfig requestConfig = RequestConfig.custom()
            .setSocketTimeout(socketTimeout)
            .setConnectTimeout(connectTimeout).build();
            
            httpPost.setConfig(requestConfig);
            
            httpPost.setHeader("Content-Type","application/json;charset=UTF-8");
//            httpPost.setHeader("SOAPAction", soapAction);
        
        
        
            StringEntity data = new StringEntity(soapXml,
            Charset.forName("UTF-8"));
            httpPost.setEntity(data);
            CloseableHttpResponse response = httpclient.execute(httpPost);
            
            HttpEntity httpEntity = response.getEntity();
            if (httpEntity != null) {
            // 打印響應內容
            retStr = EntityUtils.toString(httpEntity, "UTF-8");
            }
            // 釋放資源
            httpclient.close();
            
            
        } catch (Exception e) {
            System.out.println("請求失敗:/n" + e);
        }
            return retStr;
    }
    
    
    
    public static String doGetHttpClient(String url) throws ParseException, IOException{
//        String path = "http://xxx";
        String path = url;//請求的url地址
        
        String resultStr = "";
        
        
        
        //1.創建客戶端訪問服務器的httpclient對象   打開瀏覽器
//        1、創建httpClient
        CloseableHttpClient httpclient = HttpClients.createDefault();
        //2.以請求的連接地址創建get請求對象     瀏覽器中輸入網址
        HttpGet httpget = new HttpGet(path);
        
     
        //username:password--->訪問的用戶名,密碼,並使用base64進行加密,將加密的字節信息轉化為string類型,encoding--->token
        String encoding = DatatypeConverter.printBase64Binary("xxx:xxx".getBytes("UTF-8"));


        httpget.setHeader("Authorization", "Basic " +encoding);
        //3.向服務器端發送請求 並且獲取響應對象  瀏覽器中輸入網址點擊回車
        HttpResponse response = httpclient.execute(httpget);
        //4.獲取響應對象中的響應碼
        StatusLine statusLine = response.getStatusLine();//獲取請求對象中的響應行對象
        int responseCode = statusLine.getStatusCode();//從狀態行中獲取狀態碼

        System.out.println(responseCode);
        if (responseCode == 200) {
            //5.  可以接收和發送消息
            HttpEntity entity = response.getEntity();
            //6.從消息載體對象中獲取操作的讀取流對象
            InputStream input = entity.getContent();
            BufferedReader br = new BufferedReader(new InputStreamReader(input));
            String str1 = br.readLine();
            String result = new String(str1.getBytes("gbk"), "utf-8");
            System.out.println("服務器的響應結果:" + result);
            resultStr = result;
            br.close();
            input.close();
         // 釋放資源
            httpclient.close();
        } else {
            System.out.println("響應失敗!");
        }
        
        return resultStr;
    }
    
    
    
    
    //=========================忽略SSL證書的POST, GET請求======================================
    
    
    
    public static String testPostNoSSL(String postUrl, String paramJson,String token) {
        String resultStr = "";  //返回結果
        try {
            
//            1、創建httpClient
//            CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpClient buildSSLCloseableHttpClient = buildSSLCloseableHttpClient();
            
            System.setProperty("jsse.enableSNIExtension", "false");
            HttpPost httpPost = new HttpPost(postUrl);
            

            httpPost.setHeader("Authorization", "Bearer " +token);
            
            
            
            // 設置請求和傳輸超時時間
            RequestConfig requestConfig = RequestConfig.custom()
            .setSocketTimeout(socketTimeout)
            .setConnectTimeout(connectTimeout).build();
            
            httpPost.setConfig(requestConfig);
            
            httpPost.setHeader("Content-Type","application/json;charset=UTF-8");
            
            //放入請求參數
            StringEntity data = new StringEntity(paramJson,Charset.forName("UTF-8"));
            httpPost.setEntity(data);
            //發送請求,接收結果
            CloseableHttpResponse response = buildSSLCloseableHttpClient.execute(httpPost);
            
            //4.獲取響應對象中的響應碼
            StatusLine statusLine = response.getStatusLine();//獲取請求對象中的響應行對象
            int responseCode = statusLine.getStatusCode();//從狀態行中獲取狀態碼

            System.out.println(responseCode);
            
            if (responseCode == 200) {
                // 打印響應內容
                resultStr = EntityUtils.toString(response.getEntity(), "UTF-8");
                
                //5.  可以接收和發送消息
                HttpEntity entity = response.getEntity();
                //6.從消息載體對象中獲取操作的讀取流對象
                InputStream input = entity.getContent();
                
                
                
            } else {
                System.out.println("響應失敗! : " + response.toString());
            }
            buildSSLCloseableHttpClient.close();
            
            
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        return resultStr;
    }
    
    
    
    
    
    /**
     * 
     * @Description: 忽略SSL證書的get請求
     * @author: zhouruntao
     * @date: 2019年11月14日上午10:57:31
     */
    public static String testGetNoSSL(String url){
        String resultStr = "";//返回結果
        
        try {
            CloseableHttpClient buildSSLCloseableHttpClient = buildSSLCloseableHttpClient();
            System.setProperty("jsse.enableSNIExtension", "false");
            HttpGet httpGet = new HttpGet(url);
            
            
            
             //username:password--->訪問的用戶名,密碼,並使用base64進行加密,將加密的字節信息轉化為string類型,encoding--->token
            String encoding = DatatypeConverter.printBase64Binary("ed800cb6-f012-478a-ad94-e095adb74677:9c1f4563-589e-4494-a182-3f1c4b321c29".getBytes("UTF-8"));

//            httpget.setHeader("username", "ed800cb6-f012-478a-ad94-e095adb74677");
//            httpget.setHeader("password", "9c1f4563-589e-4494-a182-3f1c4b321c29");
            httpGet.setHeader("Authorization", "Basic " +encoding);
            
            
            HttpResponse response = buildSSLCloseableHttpClient.execute(httpGet);
            //4.獲取響應對象中的響應碼
            StatusLine statusLine = response.getStatusLine();//獲取請求對象中的響應行對象
            int responseCode = statusLine.getStatusCode();//從狀態行中獲取狀態碼

            System.out.println(responseCode);
            if (responseCode == 200) {
                
                //5.  可以接收和發送消息
                HttpEntity entity = response.getEntity();
                //6.從消息載體對象中獲取操作的讀取流對象
                InputStream input = entity.getContent();
                BufferedReader br = new BufferedReader(new InputStreamReader(input));
                String str1 = br.readLine();
                String result = new String(str1.getBytes("gbk"), "utf-8");
                System.out.println("服務器的響應結果:" + result);
                resultStr = result;
                br.close();
                input.close();
             // 釋放資源
                buildSSLCloseableHttpClient.close();
            }
            
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return resultStr;
        
    }
    
    
    /**
     * ============忽略證書
     */
    private static CloseableHttpClient buildSSLCloseableHttpClient()
            throws Exception {
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null,
                new TrustStrategy() {
                    // 信任所有
                    @Override
                    public boolean isTrusted(X509Certificate[] chain,
                            String authType) throws CertificateException {
                        return true;
                    }
                }).build();
        // ALLOW_ALL_HOSTNAME_VERIFIER:這個主機名驗證器基本上是關閉主機名驗證的,實現的是一個空操作,並且不會拋出javax.net.ssl.SSLException異常。
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslContext, new String[] { "TLSv1" }, null,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        return HttpClients.custom().setSSLSocketFactory(sslsf).build();
    }

    

   

}

 


免責聲明!

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



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