我的Android進階之旅------>Android關於HttpsURLConnection一個忽略Https認證是否正確的Https請求工具類

來源:互聯網
上載者:User

標籤:

       下面是一個Android HttpsURLConnection忽略Https認證是否正確的Https請求工具類,不需要驗證伺服器端認證是否正確



import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.UnsupportedEncodingException;import java.net.HttpURLConnection;import java.net.URL;import java.net.URLEncoder;import java.security.KeyManagementException;import java.security.NoSuchAlgorithmException;import java.security.NoSuchProviderException;import java.security.cert.CertificateException;import java.security.cert.X509Certificate;import java.util.Map;import java.util.Map.Entry;import javax.net.ssl.HostnameVerifier;import javax.net.ssl.HttpsURLConnection;import javax.net.ssl.SSLContext;import javax.net.ssl.SSLSession;import javax.net.ssl.SSLSocketFactory;import javax.net.ssl.TrustManager;import javax.net.ssl.X509TrustManager;/** * 忽略Https認證是否正確的Https Post請求工具類 * <p/> * created by OuyangPeng on 2016/1/17. */public class HttpUtil {    private static final String DEFAULT_CHARSET = "UTF-8"; // 預設字元集    private static final String _GET = "GET"; // GET    private static final String _POST = "POST";// POST    /**     * 初始化http請求參數     */    private static HttpURLConnection initHttp(String url, String method, Map<String, String> headers)            throws IOException {        URL _url = new URL(url);        HttpURLConnection http = (HttpURLConnection) _url.openConnection();        // 連線逾時        http.setConnectTimeout(25000);        // 讀取逾時 --伺服器響應比較慢,增大時間        http.setReadTimeout(25000);        http.setRequestMethod(method);        http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");        http.setRequestProperty("User-Agent",                "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");        if (null != headers && !headers.isEmpty()) {            for (Entry<String, String> entry : headers.entrySet()) {                http.setRequestProperty(entry.getKey(), entry.getValue());            }        }        http.setDoOutput(true);        http.setDoInput(true);        http.connect();        return http;    }    /**     * 初始化http請求參數     */    private static HttpsURLConnection initHttps(String url, String method, Map<String, String> headers)            throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {        TrustManager[] tm = {new MyX509TrustManager()};        SSLContext sslContext = SSLContext.getInstance("SSL");        sslContext.init(null, tm, new java.security.SecureRandom());        // 從上述SSLContext對象中得到SSLSocketFactory對象          SSLSocketFactory ssf = sslContext.getSocketFactory();        URL _url = new URL(url);        HttpsURLConnection http = (HttpsURLConnection) _url.openConnection();        // 設定網域名稱校正        http.setHostnameVerifier(new TrustAnyHostnameVerifier());        http.setSSLSocketFactory(ssf);        // 連線逾時        http.setConnectTimeout(25000);        // 讀取逾時 --伺服器響應比較慢,增大時間        http.setReadTimeout(25000);        http.setRequestMethod(method);        http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");        http.setRequestProperty("User-Agent",                "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");        if (null != headers && !headers.isEmpty()) {            for (Entry<String, String> entry : headers.entrySet()) {                http.setRequestProperty(entry.getKey(), entry.getValue());            }        }        http.setDoOutput(true);        http.setDoInput(true);        http.connect();        return http;    }    /**     * get請求     */    public static String get(String url, Map<String, String> params, Map<String, String> headers) {        StringBuffer bufferRes = null;        try {            HttpURLConnection http = null;            if (isHttps(url)) {                http = initHttps(initParams(url, params), _GET, headers);            } else {                http = initHttp(initParams(url, params), _GET, headers);            }            InputStream in = http.getInputStream();            BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));            String valueString = null;            bufferRes = new StringBuffer();            while ((valueString = read.readLine()) != null) {                bufferRes.append(valueString);            }            in.close();            if (http != null) {                http.disconnect();// 關閉串連            }            return bufferRes.toString();        } catch (Exception e) {            e.printStackTrace();            return null;        }    }    /**     * get請求     */    public static String get(String url) {        return get(url, null);    }    /**     * get請求     */    public static String get(String url, Map<String, String> params) {        return get(url, params, null);    }    /**     * post請求     */    public static String post(String url, String params, Map<String, String> headers) {        StringBuffer bufferRes = null;        try {            HttpURLConnection http = null;            if (isHttps(url)) {                http = initHttps(url, _POST, headers);            } else {                http = initHttp(url, _POST, headers);            }            OutputStream out = http.getOutputStream();            out.write(params.getBytes(DEFAULT_CHARSET));            out.flush();            out.close();            InputStream in = http.getInputStream();            BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));            String valueString = null;            bufferRes = new StringBuffer();            while ((valueString = read.readLine()) != null) {                bufferRes.append(valueString);            }            in.close();            if (http != null) {                http.disconnect();// 關閉串連            }            return bufferRes.toString();        } catch (Exception e) {            e.printStackTrace();            return null;        }    }    /**     * post請求     */    public static String post(String url, Map<String, String> params) {        return post(url, map2Url(params), null);    }    /**     * post請求     */    public static String post(String url, Map<String, String> params, Map<String, String> headers) {        return post(url, map2Url(params), headers);    }    /**     * 初始化參數     */    public static String initParams(String url, Map<String, String> params) {        if (null == params || params.isEmpty()) {            return url;        }        StringBuilder sb = new StringBuilder(url);        if (url.indexOf("?") == -1) {            sb.append("?");        }        sb.append(map2Url(params));        return sb.toString();    }    /**     * map轉url參數     */    public static String map2Url(Map<String, String> paramToMap) {        if (null == paramToMap || paramToMap.isEmpty()) {            return null;        }        StringBuffer url = new StringBuffer();        boolean isfist = true;        for (Entry<String, String> entry : paramToMap.entrySet()) {            if (isfist) {                isfist = false;            } else {                url.append("&");            }            url.append(entry.getKey()).append("=");            String value = entry.getValue();            if (null == value || "".equals(value.trim())) {                try {                    url.append(URLEncoder.encode(value, DEFAULT_CHARSET));                } catch (UnsupportedEncodingException e) {                    e.printStackTrace();                }            }        }        return url.toString();    }    /**     * 檢測是否https     */    private static boolean isHttps(String url) {        return url.startsWith("https");    }    /**     * 不進行主機名稱確認     */    private static class TrustAnyHostnameVerifier implements HostnameVerifier {        public boolean verify(String hostname, SSLSession session) {            return true;        }    }    /**     * 信任所有主機 對於任何認證都不做SSL檢測     * 安全驗證機制,而Android採用的是X509驗證     */    private static class MyX509TrustManager implements X509TrustManager {        public X509Certificate[] getAcceptedIssuers() {            return null;        }        @Override        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {        }        @Override        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {        }    }}



可以參考以下幾篇文章:

http://www.blogjava.net/stevenjohn/archive/2012/08/16/385569.html

http://blog.csdn.net/sunny243788557/article/details/38874153

http://blog.csdn.net/liangweiwei130/article/details/8845024

http://www.xuebuyuan.com/1788389.html



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

  歐陽鵬  歡迎轉載,與人分享是進步的源泉!

  轉載請保留原文地址:http://blog.csdn.net/ouyang_peng

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


我的Android進階之旅------>Android關於HttpsURLConnection一個忽略Https認證是否正確的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.