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

Date: 2020nov7 OS: Android Language: Java Keywords: TLS, SSL Q. Android: Use SSLSocket as client (eg https) A.
final int PORT = 443; final String host = "www.bing.com"; final String CRLF = "\r\n"; 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)); printWriter.print("GET / HTTP/1.1 + CRLF); printWriter.print(CRLF); printWriter.flush(); Log.i(Main.LOG_TAG, "MyHttps: sent request"); // Read inputStream // More ... socket.close();
In most cases its better to use HttpClient (for non-Android Java 12+), URLConnection (Android 1+) - these support SSL/TLS.