In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article will explain in detail how android httpClient supports HTTPS access, and the content of the article is of high quality, so the editor will share it with you for reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.
The Android https request address in the project encountered this exception (no terminal authentication):
Javax.net.ssl.SSLPeerUnverifiedException: No peer certificate
There is no terminal authentication in SSL protocol.
Did not encounter the problem, so helplessly to find du Niang.
After reading a lot of God's blog, the solution is as follows:
/ * Post request connection to Https service * @ param serverURL request address * @ param jsonStr request message * @ return * @ throws Exception * / public static synchronized String doHttpsPost (String serverURL, String jsonStr) throws Exception {/ / Parameter HttpParams httpParameters = new BasicHttpParams (); / / set connection timeout HttpConnectionParams.setConnectionTimeout (httpParameters, 3000) / / set socket timeout HttpConnectionParams.setSoTimeout (httpParameters, 3000); / / get HttpClient object (authentication) HttpClient hc = initHttpClient (httpParameters); HttpPost post = new HttpPost (serverURL); / / send data type post.addHeader ("Content-Type", "application/json;charset=utf-8"); / / accept data type post.addHeader ("Accept", "application/json") / request message StringEntity entity = new StringEntity (jsonStr, "UTF-8"); post.setEntity (entity); post.setParams (httpParameters); HttpResponse response = null; try {response = hc.execute (post);} catch (UnknownHostException e) {throw new Exception ("Unable to access" + e.getLocalizedMessage ());} catch (SocketException e) {e.printStackTrace () } int sCode = response.getStatusLine (). GetStatusCode (); if (sCode = = HttpStatus.SC_OK) {return EntityUtils.toString (response.getEntity ());} else throw new Exception ("StatusCode is" + sCode);} private static HttpClient client = null / * * initialize the HttpClient object * @ param params * @ return * / public static synchronized HttpClient initHttpClient (HttpParams params) {if (client = = null) {try {KeyStore trustStore = KeyStore.getInstance (KeyStore.getDefaultType ()); trustStore.load (null, null); SSLSocketFactory sf = new SSLSocketFactoryImp (trustStore) / / allow authentication sf.setHostnameVerifier (SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER) for all hosts; HttpProtocolParams.setVersion (params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset (params, HTTP.UTF_8); / / set http and https to support SchemeRegistry registry = new SchemeRegistry () Registry.register (new Scheme ("http", PlainSocketFactory.getSocketFactory (), 80); registry.register (new Scheme ("https", sf, 443)); ClientConnectionManager ccm = new ThreadSafeClientConnManager (params, registry); return new DefaultHttpClient (ccm, params);} catch (Exception e) {e.printStackTrace () Return new DefaultHttpClient (params);}} return client;} public static class SSLSocketFactoryImp extends SSLSocketFactory {final SSLContext sslContext = SSLContext.getInstance ("TLS"); public SSLSocketFactoryImp (KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {super (truststore) TrustManager tm = new X509TrustManager () {public java.security.cert.X509Certificate [] getAcceptedIssuers () {return null } @ Override public void checkClientTrusted (java.security.cert.X509Certificate [] chain String authType) throws java.security.cert.CertificateException {} @ Override public void checkServerTrusted (java.security.cert.X509Certificate [] chain String authType) throws java.security.cert.CertificateException {}} SslContext.init (null, new TrustManager [] {tm}, null);} @ Override public Socket createSocket (Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {return sslContext.getSocketFactory (). CreateSocket (socket, host, port, autoClose);} @ Override public Socket createSocket () throws IOException {return sslContext.getSocketFactory (). CreateSocket () }}
Under run, the little hand shivers to the test button and takes a deep breath, huh? It's not responding. Horse egg, the worker thread forgot start (), alas, again under run, finally a little reaction, miraculously did not report the previous javax.net.ssl.SSLPeerUnverifiedException: No peer certificate exception. The data on the server is returned normally.
Analyze the problem:
HTTPS: hypertext secure transfer protocol, compared with HTTP, there is one more SSL/TSL authentication process, port 443.
The 1.peer terminal sends a request,https server to return an identity information (including ca authority and encryption public key, etc.) in the form of a certificate.
two。 After obtaining the certificate, verify the validity of the certificate.
3. A key is randomly generated and encrypted with the public key in the certificate.
The 4.request https server sends the key encrypted with the public key to the https server.
The 5.https server decrypts it with its own key to obtain random values.
6. After that, the data transmitted by both parties are encrypted with this key to communicate.
Once the HTTPS process is clear, the problem becomes obvious, and when the certificate is validated, it cannot be verified.
The solution provided above is to add a default trust to all certificates. In order to pass the next communication.
However, the problem has been solved. But I think it's still unreliable (it's a little dangerous to trust all certificates). Continue to crackle and search the Internet. Another solution has been found, and the process goes something like this:
1. The browser accesses the https address, saves the prompted certificate locally, and places it in the assets directory in the android project.
two。 Import the certificate as follows.
3. Add the certificate as trust.
Public static String requestHTTPSPage (Context context, String mUrl) {InputStream ins = null; String result = ""; try {ins = context.getAssets () .open ("my.key"); / / the downloaded certificate is placed in the assets directory in the project CertificateFactory cerFactory = CertificateFactory.getInstance ("X.509"); Certificate cer = cerFactory.generateCertificate (ins) KeyStore keyStore = KeyStore.getInstance ("PKCS12", "BC"); keyStore.load (null, null); keyStore.setCertificateEntry ("trust", cer); SSLSocketFactory socketFactory = new SSLSocketFactory (keyStore); Scheme sch = new Scheme ("https", socketFactory, 443); HttpClient mHttpClient = new DefaultHttpClient (); mHttpClient.getConnectionManager (). GetSchemeRegistry (). Register (sch) BufferedReader reader = null; try {HttpGet request = new HttpGet (); request.setURI (new URI (mUrl)); HttpResponse response = mHttpClient.execute (request); if (response.getStatusLine (). GetStatusCode ()! = 200) {request.abort (); return result } reader = new BufferedReader (new InputStreamReader (response .getEntity (). GetContent ()); StringBuffer buffer = new StringBuffer (); String line = null; while ((line = reader.readLine ())! = null) {buffer.append (line) } result = buffer.toString ();} catch (Exception e) {e.printStackTrace ();} finally {if (reader! = null) {reader.close () } catch (Exception e) {e.printStackTrace ();} finally {try {if (ins! = null) ins.close ();} catch (IOException e) {e.printStackTrace () }} return result; about how android httpClient supports HTTPS access is shared here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.