Tuesday, 21 August 2012

How to read HTTPs URL in JAVA


Hi,

Below are a java method that read HTTS response from URL.I hope,it will be helpful. 

// @required import files 
import java.io.IOException;
import java.io.StringWriter;
import java.net.HttpURLConnection;

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

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
//end


// java method
@SuppressWarnings("deprecation")
    private static String getHttpResponseAsString(String uri) throws Exception {
        TrustManager[] trustAllCerts = new TrustManager[]{
            new X509TrustManager() {
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
                public void checkClientTrusted(
                    java.security.cert.X509Certificate[] certs, String authType) {
                }
                public void checkServerTrusted(
                    java.security.cert.X509Certificate[] certs, String authType) {
                }
            }
        };
        HttpResponse resp = null;
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
  
            SchemeRegistry registry = new SchemeRegistry();
            SSLSocketFactory socketFactory = new SSLSocketFactory(sc);
            socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
            HttpParams params = new BasicHttpParams();
            registry.register(new Scheme("https", socketFactory, 443));
            SingleClientConnManager mgr = new SingleClientConnManager(params, registry);
            DefaultHttpClient httpClient = new DefaultHttpClient(mgr, params);
          
            HttpGet get = new HttpGet(uri);
            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("admin", "password");
          
            httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials);
            resp = httpClient.execute(get);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            throw new Exception(e.getMessage());
        } catch (IOException e) {
            throw new Exception(e.getMessage());
        } catch (Exception e1) {
            throw new RuntimeException(e1);
        }
        if (null == resp) {
            throw new Exception("Got Status Code : 100");
        }
        if (resp.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
            StringWriter writer = new StringWriter();
            try {
                IOUtils.copy(resp.getEntity().getContent(), writer);
                return writer.toString();
            } catch (IOException e) {
                throw new Exception(e.getMessage());
            }
        } else {
            throw new Exception("Got Status Code : " + resp.getStatusLine().getStatusCode());
        }
    }

No comments:

Post a Comment