Wednesday, July 9, 2008

Java HTPPS SSL Client

HTTPS secure HTTP connection , HTTP over secure socket layer (SSL).
To establish an HTTPS connection to a remote server , you should use the certificate obtained by the server. This certificate is validated using a local trust store. Default trust store is /lib/security/cacerts. You can define another trust store using keytool application in /bin. Certificates can be added to trust store with keytool application also.

You should give trust store parameter to JVM like this :

-Djavax.net.ssl.trustStore=/mypath/my.keystore
-Djavax.net.ssl.trustStorePassword=mypassword

Here is the sample code to create an HTTPS connection:


package javacream;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URLEncoder;
import java.security.Security;

import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

public class HTTPSClient {

public static void main(String[] args) {
String resp = sendReq("myserver.mydomain.com",
"/myapp/findbookservlet", "bookID=2323");
System.out.println(resp);
}

// Uses post to fetch data , return null if it fails.
public static String sendReq(String host, String path, String data) {

int port = 443; // default https port

BufferedWriter wr = null;
BufferedReader in = null;
SSLSocket socket = null;

try {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory
.getDefault();
socket = (SSLSocket) factory.createSocket(host, port);
String[] supported = socket.getSupportedCipherSuites();
socket.setEnabledCipherSuites(supported);
String encData = URLEncoder.encode(data, "UTF-8");

wr = new BufferedWriter(new OutputStreamWriter(socket
.getOutputStream(), "UTF8"));
wr.write("POST " + path + " HTTP/1.0\r\n");
wr.write("Content-Length: " + data.length() + "\r\n");
wr.write("Content-Type: application/x-www-form-urlencoded\r\n");
wr.write("\r\n");
wr.write(data);
wr.flush();
// read response
in = new BufferedReader(new InputStreamReader(socket
.getInputStream(), "UTF-8"));
int c;
StringBuffer sb = new StringBuffer();

while ((c = in.read()) != -1) {
sb.append((char) c);
}
System.out.println("SSL Response:" + sb.toString());
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (wr != null)
try {
wr.close();
} catch (IOException e2) {
e2.printStackTrace();
}
if (in != null)
try {
in.close();
} catch (IOException e1) {
e1.printStackTrace();
}
if (socket != null)
try {
socket.close();
} catch (IOException e2) {
e2.printStackTrace();
}

}

return null;
}
}

No comments: