Programming Tips - Android: Use SSLSocket as client (eg https)

Date: 2020nov7 OS: Android Language: Java Q. Android: Use SSLSocket as client (eg https) A.
final int PORT = 443; final String host = "www.bing.com"; SocketFactory sf = SSLSocketFactory.getDefault(); SSLSocket socket = (SSLSocket) sf.createSocket(host, PORT); HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier(); SSLSession session = socket.getSession(); if (!hv.verify(host, session)) { Log.i(Main.LOG_TAG, "MyHttps: Expected " + host + ", found " + session.getPeerPrincipal()); return; } Log.i(Main.LOG_TAG, "MyHttps: hostname is ok"); // At this point SSLSocket performed certificate verification and // we have performed hostname verification, so it is safe to proceed. socket.startHandshake(); Log.i(Main.LOG_TAG, "MyHttps: handshake is ok"); InputStream inputStream = socket.getInputStream(); OutputStream outputStream = socket.getOutputStream(); PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(outputStream)); final String CRLF = "\r\n"; printWriter.print("GET / HTTP/1.1 + CRLF); printWriter.print(CRLF); printWriter.flush(); Log.i(Main.LOG_TAG, "MyHttps: sent request"); // Read inputSteam // More ... socket.close();