1. 程式人生 > >Java Https工具類,Java Https Post請求

Java Https工具類,Java Https Post請求

Java Https工具類,Java Https Post請求

 

================================

©Copyright 蕃薯耀 2019-01-08

http://fanshuyao.iteye.com/

 

一、使用jsoup進行連線

 

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509TrustManager;

import org.jsoup.Connection;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;

public class HttpsUtils {
	/**
     * 請求超時時間
     */
    private static final int TIME_OUT = 120000;

    /**
     * Https請求
     */
    private static final String HTTPS = "https";

    /**
     * 返回成功狀態碼
     */
    private static final int OK = 200;

    /**
     * 純字串引數post請求
     * 
     * @param url 請求URL地址
     * @param paramMap 請求字串引數集合
     * @return 伺服器返回內容
     * @throws Exception
     */
    public static String post(String url, Map<String, String> paramMap) throws Exception {
        Response response = doPostRequest(url, paramMap, null);
        return response.body();
    }

    /**
     * 帶上傳檔案的post請求
     * 
     * @param url 請求URL地址
     * @param paramMap 請求字串引數集合
     * @param fileMap 請求檔案引數集合
     * @return 伺服器返回內容
     * @throws Exception
     */
    public static String post(String url, Map<String, String> paramMap, Map<String, File> fileMap) throws Exception {
        Response response = doPostRequest(url, paramMap, fileMap);
        return response.body();
    }

    /**
     * 執行post請求
     * 
     * @param url 請求URL地址
     * @param paramMap 請求字串引數集合
     * @param fileMap 請求檔案引數集合
     * @return 伺服器相應物件
     * @throws Exception
     */
    public static Response doPostRequest(String url, Map<String, String> paramMap, Map<String, File> fileMap) throws Exception {
        if (null == url || url.isEmpty()) {
            throw new Exception("The request URL is blank.");
        }

        // 如果是Https請求
        if (url.startsWith(HTTPS)) {
            getTrust();
        }
        Connection connection = Jsoup.connect(url);
        connection.method(Connection.Method.POST);
        connection.timeout(TIME_OUT);
        connection.header("Content-Type", "multipart/form-data");
        connection.ignoreHttpErrors(true);
        connection.ignoreContentType(true);

        // 新增字串類引數
        if (null != paramMap && !paramMap.isEmpty()) {
            connection.data(paramMap);
        }

        // 新增檔案引數
        if (null != fileMap && !fileMap.isEmpty()) {
            InputStream in = null;
            File file = null;
            Set<Entry<String, File>> set = fileMap.entrySet();
            try {
                for (Entry<String, File> e : set) {
                    file = e.getValue();
                    in = new FileInputStream(file);
                    connection.data(e.getKey(), file.getName(), in);
                }
            } catch (FileNotFoundException e) {
                throw new Exception(e.getMessage());
            }
        }

        try {
            Response response = connection.execute();
            if (response.statusCode() != OK) {
                throw new Exception(response.statusMessage());
            }
            return response;
        } catch (IOException e) {
            throw new Exception(e);
        }
    }

    /**
     * 獲取伺服器信任
     */
    private static void getTrust() {
        try {
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {

                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, new X509TrustManager[] { new X509TrustManager() {

                public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}

                public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}

                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
            } }, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

在可以連線網際網路的時候沒有問題,但在公司內網,訪問不到網際網路,只能訪問某些介面時會出錯,如下:

java.lang.Exception: javax.net.ssl.SSLKeyException: FATAL Alert:BAD_CERTIFICATE - A corrupt or unuseable certificate was received.

 

 

 

二、使用原生的HttpURLConnection連線

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.CertificateException;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.security.cert.X509Certificate;


public class HttpsClientUtil {
	 private final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
	        public boolean verify(String hostname, SSLSession session) {
	            return true;
	        }
	    };

	    private static void trustAllHosts() {
	        // Create a trust manager that does not validate certificate chains
	        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
	            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
	                return new java.security.cert.X509Certificate[]{};
	            }

	            public void checkClientTrusted(X509Certificate[] chain, String authType) {
	            }

	            public void checkServerTrusted(X509Certificate[] chain, String authType) {
	            }

				@Override
				public void checkClientTrusted(
						java.security.cert.X509Certificate[] arg0, String arg1)
						throws CertificateException {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void checkServerTrusted(
						java.security.cert.X509Certificate[] arg0, String arg1)
						throws CertificateException {
					// TODO Auto-generated method stub
					
				}
	        }};
	        // Install the all-trusting trust manager
	        try {
	            SSLContext sc = SSLContext.getInstance("TLS");
	            sc.init(null, trustAllCerts, new java.security.SecureRandom());
	            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	    }

	    public static String sendHtpps(String a,String url) {
	        String result = "";
	        OutputStreamWriter out = null;
	        BufferedReader in = null;
	        HttpURLConnection conn;
	        try {
	            trustAllHosts();				
	            URL realUrl = new URL(null,url,new sun.net.www.protocol.https.Handler());
	            //通過請求地址判斷請求型別(http或者是https)
	            if (realUrl.getProtocol().toLowerCase().equals("https")) {
	                HttpsURLConnection https = (HttpsURLConnection) realUrl.openConnection();
	                https.setHostnameVerifier(DO_NOT_VERIFY);
	                conn = https;
	            } else {
	                conn = (HttpURLConnection) realUrl.openConnection();
	            }
	            // 設定通用的請求屬性
	            conn.setRequestProperty("accept", "*/*");
	            conn.setRequestProperty("connection", "Keep-Alive");
	            conn.setRequestProperty("user-agent",
	                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
	            conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
	            // 傳送POST請求必須設定如下兩行
	            conn.setDoOutput(true);
	            conn.setDoInput(true);
	            // 獲取URLConnection物件對應的輸出流
	            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
	            out.write(a);
	            //錯誤方式,這種方式容易出現亂碼
	            // PrintWriter out = new PrintWriter(connection.getOutputStream());  
	            /*out.print(a);*/
	            // flush輸出流的緩衝
	            out.flush();
	            // 定義BufferedReader輸入流來讀取URL的響應
	            in = new BufferedReader(
	                    new InputStreamReader(conn.getInputStream(), "UTF-8"));
	            String line;
	            while ((line = in.readLine()) != null) {
	            	result += line;
	            }
	        } catch (Exception e) {
	        	result = "sendHtpps error";
	            e.printStackTrace();
	        } finally {// 使用finally塊來關閉輸出流、輸入流
	            try {
	                if (out != null) {
	                    out.close();
	                }
	                if (in != null) {
	                    in.close();
	                }
	            } catch (IOException ex) {
	                ex.printStackTrace();
	            }
	        }
	        return result;
	    }
}

 

 

 

 

================================

©Copyright 蕃薯耀 2019-01-08

http://fanshuyao.iteye.com/