Friday, May 21, 2010

HttpsUrlConnection Example Code

/**
* JavaHttpsUrlConnectionReader
*
*
*@author Palaniappan S
*/
import java.io.*;
import java.net.*;
import java.security.cert.X509Certificate;
import java.util.Properties;
import javax.net.ssl.*;


public class JavaHttpsUrlConnectionReader implements javax.net.ssl.X509TrustManager {

public static void main(String[] args) throws Exception {

String output = new JavaHttpsUrlConnectionReader().doHttpsUrlConnectionAction("https://somesecuresite.com");
System.out.println("Output : "+output);

}

public String doHttpsUrlConnectionAction(String desiredUrl) throws Exception {

URL url;
int responseCode=0;
StringBuffer responseData = new StringBuffer( );
//Uncomment below lines of code if any proxy enabled in the network you are using
//Properties props = System.getProperties();
//props.put("https.proxyHost", "127.0.0.1");
//props.put("https.proxyPort", "8080");

// ###########
SSLContext sc = SSLContext.getInstance("SSLv3");
TrustManager[] tma = { new JavaHttpsUrlConnectionReader() };
sc.init(null, tma, null);
SSLSocketFactory ssf = sc.getSocketFactory();
HttpsURLConnection.setDefaultSSLSocketFactory(ssf);
// ###########
HttpsURLConnection connection = null;

String nurl = desiredUrl;
HostnameVerifier hv = new HostnameVerifier()
{
public boolean verify(String urlHostName, SSLSession session)
{
System.out.println("Warning: URL Host: " + urlHostName + " vs. "
+ session.getPeerHost());
return true;
}
};
// Now you are telling the JRE to trust any https server.
// If you know the URL that you are connecting to then this should not be a problem
// trustAllHttpsCertificates();
HttpsURLConnection.setDefaultHostnameVerifier(hv);

try {
url = new URL(nurl);
connection = (HttpsURLConnection) url.openConnection();
System.out.println("Conn established "+connection);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
responseCode = connection.getResponseCode();
System.out.println("response code : "+responseCode);
connection.connect();
} catch(Exception e) {
System.err.println(e);
}
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String _ResData = null;
while ((_ResData = reader.readLine()) != null)
{
responseData.append(_ResData);
//_ResData = sckStream.readLine();
}
System.out.println("Received Data: "+ responseData.toString());

} catch (Exception e) {
System.err.println(e);
}
finally
{
// close the reader; this can throw an exception too, so
// wrap it in another try/catch block.
if (reader != null)
{
try
{
connection.disconnect();
reader.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
return responseData.toString();
}

// TrustManager Methods
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}

public void checkServerTrusted(X509Certificate[] chain, String authType) {
}

public X509Certificate[] getAcceptedIssuers() {
return null;
}

}

Hope the above code helped you......

Best Regards,
Palaniappan

3 comments:

  1. Hi,

    I'm having an issue with HttpsUrlConnection. I'm writing my request to the connection outputstream but I don't get anything in inputstream.

    So I tried with your code by setting my URL but still i have the same issue.

    Do you have any suggestions?

    Thanks,
    Darshana

    ReplyDelete
  2. worked like a charm, but i dint like when we are ignoring the Certificate.

    ReplyDelete
  3. WOW !!! Palani kalakitinga...

    ReplyDelete