My Android Advanced tour------>android about httpsurlconnection an HTTPS request tool class that ignores the correct HTTPS certificate

Source: Internet
Author: User

Below is an Android httpsurlconnection HTTPS request tool class that ignores the correct HTTPS certificate and does not need to verify that the server-side 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;/** * Ignore HTTPS certificate is correct HTTPS POST request tool class * <p/> * 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 HTTP request parameters */private static Httpurlconn Ection inithttp (string url, string method, Map<string, string> headers) throws IOException {URL _        url = new URL (URL);        HttpURLConnection http = (httpurlconnection) _url.openconnection ();        Connection Timeout http.setconnecttimeout (25000);        Read timeout-server response is slow, increase time 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;  }/** * Initialize HTTP request parameters */private static httpsurlconnection Inithttps (string url, string method, Map<string, string> headers) throws IOException, NoSuchAlgorithmException, Nosuchproviderexception, keymanagementexcept        Ion {trustmanager[] tm = {new Myx509trustmanager ()};        Sslcontext Sslcontext = sslcontext.getinstance ("SSL");        Sslcontext.init (NULL, TM, New Java.security.SecureRandom ());        Sslsocketfactory object Sslsocketfactory SSF = Sslcontext.getsocketfactory () obtained from the above Sslcontext object;        URL _url = new URL (URL);        Httpsurlconnection http = (httpsurlconnection) _url.openconnection ();        Set the domain name check http.sethostnameverifier (new Trustanyhostnameverifier ());        Http.setsslsocketfactory (SSF);        Connection Timeout http.setconnecttimeout (25000); Read timeout--server response is slow, increase time 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 request */public static string get (string URL, map<string, string> params, map<string, Strin        g> 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 ();//Close 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<string, string> params) {return get (    URL, params, null); }/** * POST request */public static string post (string URL, stringparams, 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 ();//Close connection} return bufferres.tostring ();      } catch (Exception e) {      E.printstacktrace ();        return null; }}/** * POST request */public static string post (string URL, map<string, string> params) {Retu    RN post (URL, Map2url (params), null); }/** * POST request */public static string post (string URL, map<string, string> params, map<string, Str    ing> headers) {return post (URL, Map2url (params), headers); }/** * Initialization parameters */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 to URL parameter */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 ();    }/** * Detects if HTTPS */private static Boolean Ishttps (String URL) {return url.startswith ("https"); }/** * Do not host name confirmation */private static class Trustanyhostnameverifier implements Hostnameverifier {Publ IC Boolean verify (String hostname, sslsession session) {Return true; }}/** * Trust all hosts not to do SSL detection for any certificate * Security authentication mechanism, while Android is using X509 authentication */private static Class Myx509trustmanage        R implements X509trustmanager {public x509certificate[] Getacceptedissuers () {return null; } @Override public void checkclienttrusted (x509certificate[] chain, String authtype) throws Certificateexcep tion {} @Override public void checkservertrusted (x509certificate[] chain, String authtype) throws Ce Rtificateexception {}}}



You can refer to the following articles:

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



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

Ouyangpeng welcome reprint, sharing with people is the source of progress!

Reprint please keep the original address : Http://blog.csdn.net/ouyang_peng

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


My Android Advanced tour------>android about httpsurlconnection an HTTPS request tool class that ignores the correct HTTPS certificate

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.