Friday, July 26, 2013

HTTPS with Java

Writing https client in java is confusing. You might get different sort of exception every time. Here is a small snippet of code which always gonna work.
If not, let me know.. we will sort something out together. :)




public class LookEasyBO {
   
    private String https_url = "https://yoursecuteSiteHere.com";
    private String userName = "username"; // Add userName here
    private String password = "password"; // Add password here.
   
   
    public static void main(String[] args){
        new LookEasyBO().getDataFromURL();
   }

   
    public void getDataFromURL(){
        try {

            javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(
                new javax.net.ssl.HostnameVerifier(){
                    public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) {
                      return true;
                    }
                });

                URL url = new URL(https_url);
           
                HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
           
                String credential = userName + ":" + password;
                String basicAuth = "Basic " + Base64.encodeBytes(credential.getBytes("UTF-8"));
                con.setRequestProperty("Authorization", basicAuth);

               BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
               StringBuffer content = new StringBuffer();
               String input;
               while ((input = br.readLine()) != null){
                   content.append(input.trim());
               }
               br.close();
               System.out.println(content.toString());
                  
        } catch (Exception e) {
            e.printStackTrace();
        }
       
    }

No comments:

Post a Comment