使用java發送https的請求

來源:互聯網
上載者:User

標籤:

package api.basic;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.cert.CertificateException;
import java.util.Map;

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 java.security.cert.X509Certificate;

public class HttpsGetData {
    private static class TrustAnyTrustManager implements 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[] {};
        }
    }
 
    private static class TrustAnyHostnameVerifier implements HostnameVerifier {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }
    String _url="";
    
    Map<String,String> _params;
    
    public HttpsGetData(String url,Map<String,String> keyValueParams)
    {
        this._url=url;
        this._params=keyValueParams;
    }
    public String Do() throws Exception
    {
         String result = "";
         BufferedReader in = null;
            try {
                
                String urlStr = this._url + "&" + getParamStr();
                System.out.println("GET請求的URL為:"+urlStr);
                SSLContext sc = SSLContext.getInstance("SSL");
                sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },
                         new java.security.SecureRandom());
                URL realUrl = new URL(urlStr);
                // 開啟和URL之間的串連
                HttpsURLConnection connection = (HttpsURLConnection) realUrl.openConnection();
                //設定https相關屬性
                connection.setSSLSocketFactory(sc.getSocketFactory());
                connection.setHostnameVerifier(new TrustAnyHostnameVerifier());
                connection.setDoOutput(true);
                
                // 設定通用的請求屬性
                connection.setRequestProperty("accept", "*/*");
                connection.setRequestProperty("connection", "Keep-Alive");
                connection.setRequestProperty("user-agent",
                        "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
                // 建立實際的串連
                connection.connect();
                
                // 定義 BufferedReader輸入資料流來讀取URL的響應
                in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
                System.out.println("擷取的結果為:"+result);
            } catch (Exception e) {
                System.out.println("發送GET請求出現異常!" + e);
                //e.printStackTrace();
                throw e;
            }
            // 使用finally塊來關閉輸入資料流
            finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (Exception e2) {
                    //e2.printStackTrace();
                    throw e2;
                }
            }
            return result;
    
    }

    private String getParamStr()
    {
        String paramStr="";
        // 擷取所有回應標頭欄位
        Map<String, String> params = this._params;
        // 擷取參數列表組成參數字串
        for (String key : params.keySet()) {
            paramStr+=key+"="+params.get(key)+"&";
        }
        //去除最後一個"&"
        paramStr=paramStr.substring(0, paramStr.length()-1);
        
        return paramStr;
    }
}

使用java發送https的請求

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.