Java SocketFactory create from SSL

Description

Java SocketFactory create from SSL


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;

import javax.net.SocketFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class Main {
   public static void main(String args[]) throws Exception {
      String urlString = "https://127.0.0.1:8443/index.jsp";
      URL url = new URL(urlString);
      TrustManager[] trustAllCerts = { new X509TrustManager() {
         public X509Certificate[] getAcceptedIssuers() {
            return null;
         }//from  ww w  . j a  v  a2  s  . c o m

         public void checkClientTrusted(X509Certificate[] certs, String authType) {
         }

         public void checkServerTrusted(X509Certificate[] certs, String authType) {
         }
      } };
      SSLContext sc = SSLContext.getInstance("SSL");
      sc.init(null, trustAllCerts, new SecureRandom());
      SocketFactory factory = sc.getSocketFactory();
      Socket socket = factory.createSocket(url.getHost(), url.getPort());
      PrintWriter out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
      BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      out.println("GET " + urlString + " HTTP/1.1\n");
      String line;
      while ((line = in.readLine()) != null)
         System.out.println(line);
   }
}



PreviousNext

Related