星期一, 9月 12, 2011

[Java] HttpsUrlConnection

JAVA使用HttpsUrlConnection建立Https的Request。



package com.test.restful;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class TestHttpsURLConnection {
	
	public final static boolean DEBUG = true;
	
	public static void main(String[] args) {

		try{
			String httpsURL = " https://192.168.0.137/restful/services/auth/login";
		    URL myurl = new URL(httpsURL);
		    
		    //Use MyX509TrustManager
		    TrustManager[] trustMyCerts = new TrustManager[] { new MyX509TrustManager()};
		    
		    
		    //Trust All
//		    TrustManager[] trustMyCerts = new TrustManager[] { new X509TrustManager(){
//				@Override
//				public void checkClientTrusted(X509Certificate[] chain,
//						String authType) throws CertificateException {
//				}
//				@Override
//				public void checkServerTrusted(X509Certificate[] chain,
//						String authType) throws CertificateException {
//				}
//				@Override
//				public X509Certificate[] getAcceptedIssuers() {
//					return null;
//				}
//		    }};
		    
		    //Implement  HostnameVerifier
			HostnameVerifier hv = new HostnameVerifier()
			{
			      public boolean verify(String urlHostName, SSLSession session)
			      {
			          if(DEBUG){
			        	  System.out.println("Warning: URL Host: "+urlHostName+" vs. "+session.getPeerHost());  
			          }   
			          return urlHostName.equalsIgnoreCase(session.getPeerHost());
			      }
			};
			
			//Initial SSLContext
			SSLContext sc = SSLContext.getInstance("SSL");
			sc.init(null, trustMyCerts, new java.security.SecureRandom());   
			
			HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
			HttpsURLConnection.setDefaultHostnameVerifier(hv);
		    HttpsURLConnection con = (HttpsURLConnection)myurl.openConnection();
		   
		    
		    con.setRequestMethod("POST");
		    con.setRequestProperty("Content-Type", "application/json");
		    con.setDoInput(true);
		    con.setDoOutput(true);
		    con.setUseCaches(false);
		    con.setRequestProperty("Content-Length", "2");
		    DataOutputStream dataOs = new DataOutputStream(con.getOutputStream());
		    dataOs.writeBytes("{'username':'shinko','password':'5437'}");
		    dataOs.flush();
		    dataOs.close();
		    
		    if (DEBUG) {
		    	System.out.println("Response Code : " + con.getResponseCode());
				System.out.println("Cipher Suite : " + con.getCipherSuite());
				System.out.println("\n");
			 
				Certificate[] certs = con.getServerCertificates();
				for(Certificate cert : certs){
				   System.out.println("Cert Type : " + cert.getType());
				   System.out.println("Cert Hash Code : " + cert.hashCode());			   
				   System.out.println("Cert Public Key Algorithm : " + cert.getPublicKey().getAlgorithm());
				   System.out.println("Cert Public Key Format : " + cert.getPublicKey().getFormat());
				   System.out.println("\n");
				}
			}

		    InputStream ins = con.getInputStream();
		    InputStreamReader isr = new InputStreamReader(ins);
		    BufferedReader in = new BufferedReader(isr);
		    
		    String inputLine;
	
		    while ((inputLine = in.readLine()) != null)
		    {
		      System.out.println(inputLine);
		    }
		    in.close();
		}catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
		}

	}

}

沒有留言:

張貼留言

留個話吧:)