ssl 소켓 위에서 http 호출 예제

실행시 아래 파라미터 지정 필요. 이때 필요한 서버인증서파일 jssecacerts를 생성하기 위해 InstallCert.java 실행
-Djavax.net.ssl.trustStore=jssecacerts -Djavax.net.ssl.trustStorePassword=changeit

위의 옵션을 지정하지 않는 경우 서버인증서 파일의 기본 위치는
<jvm-home>/lib/security/cacerts

package com.gimslab.https_test;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import javax.net.SocketFactory;
import javax.net.ssl.SSLSocketFactory;


public class HttpsTest {

    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
	new HttpsTest().httpsGetTest2();
    }

    private void httpsGetTest2() throws Exception {
	int port = 443;
	String hostname = "www.google.com";

	SocketFactory socketFactory = SSLSocketFactory.getDefault();
	Socket socket = socketFactory.createSocket(hostname, port);

	OutputStream os = null;
	InputStream is = null;
	try{
	    os = socket.getOutputStream();
	    is = socket.getInputStream();

	    String str = "GET / HTTP/1.1\n\n";
	    os.write(str.getBytes());
	    os.flush();

	    byte[] buff = new byte[512];
	    int read = -1;
	    while ((read = is.read(buff, 0, buff.length)) != -1) {
		System.out.print(new String(buff, 0, read));
	    }
	}
	finally{
	    is.close();
	    os.close();
	}

	socket.close();
    }

}

Valid XHTML 1.0! Valid CSS! powered by MoniWiki
last modified 2010-07-08 19:58:03
Processing time 0.0056 sec