My Android advanced tutorial ------) an Https request tool class for Android about HttpsURLConnection that ignores Https certificate correctness

Source: Internet
Author: User

My Android advanced tutorial ------) an Https request tool class for Android about HttpsURLConnection that ignores Https certificate correctness

The following is an Https request tool for Android HttpsURLConnection to ignore whether the Https certificate is correct. You do not need to verify that the server certificate is correct.

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;/*** specifies whether the Https Post request tool class is correct for the Https certificate *

* Created by OuyangPeng on 2016/1/17. */public class HttpUtil {private static final String DEFAULT_CHARSET = "UTF-8"; // default character set private static final String _ GET = "GET "; // GET private static final String _ POST = "POST"; // POST/*** initialize the http request parameter */private static HttpURLConnection initHttp (String url, String method, Map Headers) throws IOException {URL _ url = new URL (url); HttpURLConnection http = (HttpURLConnection) _ url. openConnection (); // connection timeout http. setConnectTimeout (25000); // read timeout -- server response is slow and http is increased. 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) App LeWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36 "); if (null! = Headers &&! Headers. isEmpty () {for (Entry Entry: headers. entrySet () {http. setRequestProperty (entry. getKey (), entry. getValue () ;}} http. setDoOutput (true); http. setDoInput (true); http. connect (); return http;}/*** initialize the http request parameter */private static HttpsURLConnection initHttps (String url, String method, Map Headers) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {TrustManager [] tm = {new MyX509TrustManager ()}; SSLContext sslContext = SSLContext. getInstance ("SSL"); sslContext. init (null, tm, new java. security. secureRandom (); // obtain the SSLSocketFactory object SSLSocketFactory ssf = SSLContext from the sslContext object. getSocketFactory (); URL _ url = new URL (url); HttpsURLConne Ction http = (HttpsURLConnection) _ url. openConnection (); // sets the domain name verification http. setHostnameVerifier (new TrustAnyHostnameVerifier (); http. setSSLSocketFactory (ssf); // connection timeout http. setConnectTimeout (25000); // read timeout -- server response is slow and http is increased. setReadTimeout (25000); http. setRequestMethod (method); http. setRequestProperty ("Content-Type", "application/x-www-form-urlencoded"); http. setRequestProperty ("User-Agent", "Mozil La/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 Entry: headers. entrySet () {http. setRequestProperty (entry. getKey (), entry. getValue () ;}} http. setDoOutput (true); http. setDoInput (true); http. connect (); return http;}/*** get request */public static String get (String url, Map Params, Map 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 StringB Uffer (); while (valueString = read. readLine ())! = Null) {bufferRes. append (valueString) ;}in. close (); if (http! = Null) {http. disconnect (); // close the connection} return bufferRes. toString ();} catch (Exception e) {e. printStackTrace (); return null ;}/ *** get request */public static String get (String url) {return get (url, null );} /*** get request */public static String get (String url, Map Params) {return get (url, params, null);}/*** post Request */public static String post (String url, String params, Map 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 InputStreamRead Er (in, DEFAULT_CHARSET); String valueString = null; bufferRes = new StringBuffer (); while (valueString = read. readLine ())! = Null) {bufferRes. append (valueString) ;}in. close (); if (http! = Null) {http. disconnect (); // close the connection} return bufferRes. toString ();} catch (Exception e) {e. printStackTrace (); return null ;}/ *** post Request */public static String post (String url, Map Params) {return post (url, map2Url (params), null);}/*** post Request */public static String post (String url, Map Params, Map Headers) {return post (url, map2Url (params), headers);}/*** initialization parameter */public static String initParams (String url, Map 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 to url parameter */public static String map2Url (Map ParamToMap) {if (null = paramToMap | paramToMap. isEmpty () {return null;} StringBuffer url = new StringBuffer (); boolean isfist = true; for (Entry 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 ();}/*** check whether https */private static boolean isHttps (String url) {return url. startsWith ("https");}/*** no host name confirmation */private static class TrustAnyHostnameVerifier implements HostnameVerifier {public boolean verify (String hostname, SSLSession session) {return true ;}}/*** trust that all hosts do not perform SSL detection on any certificate * security authentication mechanism, android uses X509 verification */private static class MyX509TrustManager implements X509TrustManager {public token [] getAcceptedIssuers () {return null;} @ Override public void checkClientTrusted (token [] chain, string authType) throws CertificateException {}@ Override public void checkServerTrusted (X509Certificate [] chain, String authType) throws CertificateException {}}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.