ConnectionProtccol.HttpClient.java Source code

Java tutorial

Introduction

Here is the source code for ConnectionProtccol.HttpClient.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ConnectionProtccol;

/**
 *
 * @author harsha-1916
 */
import fileoperations.FileOperations;
import loggerapi.CustomLogger;
import java.net.MalformedURLException;
import java.net.URL;
import java.io.*;
import java.net.HttpURLConnection;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpClient {

    private static final CustomLogger loggerProperties = new CustomLogger();
    private static Logger loggerObj;

    static {
        initializeLoggerParams();
    }

    private static void initializeLoggerParams() {

        boolean isValidLogger = loggerProperties.setLoggerProperties("HTTPConnection",
                "./Logs/HTTPSConnection.%u.%g.txt");
        if (isValidLogger) {
            loggerObj = loggerProperties.getLogger();
            //loggerObj.setUseParentHandlers(false);
        }

    }

    public String OpenHTTPConnection(String URLToConnect, String fileToWrite) {
        URL url;
        HttpURLConnection con = null;
        try {
            loggerObj.log(Level.SEVERE, "Going to connect to the URL" + URLToConnect);
            url = new URL(URLToConnect);

            con = (HttpURLConnection) url.openConnection();
        } catch (MalformedURLException ex) {
            loggerObj.log(Level.SEVERE,
                    "Malformed URL Exception while trying to establish connection with MEDC portal"
                            + ex.toString());
            System.out.println("Malformed URL Exception while trying to establish connection with MEDC portal"
                    + ex.toString());
            return null;
        } catch (IOException ex) {

            loggerObj.log(Level.SEVERE,
                    "Exception while trying to establish connection with MEDC portal" + ex.toString());
            System.out.println("Exception while trying to establish connection with MEDC portal" + ex.toString());
            return null;
        }
        String result = ConnectionHandler(con, fileToWrite);
        System.out.println("result" + result);
        //loggerObj.log(Level.INFO, "The Result obtained from connecting to the URL "+ URLToConnect +"is: " +  result);
        return result;

    }

    private String ConnectionHandler(HttpURLConnection con, String fileToWrite) {
        BufferedReader br = null;
        if (con != null) {
            try {

                br = new BufferedReader(new InputStreamReader(con.getInputStream()));

                String input;
                String result = "";
                while ((input = br.readLine()) != null) {
                    FileOperations.writeObjectToFile(input + "\n", fileToWrite);
                }
                br.close();
                // loggerObj.log(Level.INFO, "Result recieved from connection is "+  result);
                return result;
            } catch (IOException e) {
                if (br != null) {
                    try {

                        br.close();
                    } catch (IOException ex) {
                        loggerObj.log(Level.SEVERE, "Exception while closing Connection " + e);
                    }
                }
                loggerObj.log(Level.SEVERE,
                        "Exception while trying to establish connection with MEDC portal" + e.toString());
                System.out
                        .println("Exception while trying to establish connection with MEDC portal" + e.toString());
                return null;

            }

        }
        return null;
    }

    /**
     *
     * @param urlParams
     * @param postParams
     *
     */
    public boolean httpPost(String url, MultipartEntityBuilder builder, UrlEncodedFormEntity formParams) {

        loggerObj.log(Level.INFO, "Inside httpsPost method");
        CloseableHttpClient httpclient = HttpClients.createDefault();

        try {
            //  HttpPost httppost = new HttpPost("https://reportsapi.zoho.com/api/harshavardhan.r@zohocorp.com/Test/Name_password?ZOHO_ACTION=IMPORT&ZOHO_OUTPUT_FORMAT=json&ZOHO_ERROR_FORMAT=json&authtoken=7ed717b94bc30455aad11ce5d31d34f9&ZOHO_API_VERSION=1.0");
            loggerObj.log(Level.INFO, "Going to post to the zoho reports api");

            HttpPost httppost = new HttpPost(url);

            //Need to understand the difference betwween multipartentitybuilder and urlencodedformentity//
            HttpEntity entity = null;
            if (builder != null) {
                entity = builder.build();
            }

            if (formParams != null) {
                entity = formParams;
            }

            httppost.setEntity(entity);
            loggerObj.log(Level.INFO, "executing request");
            System.out.println("executing request " + httppost.getRequestLine());
            CloseableHttpResponse response = null;
            try {
                response = httpclient.execute(httppost);
            } catch (IOException ex) {
                loggerObj.log(Level.INFO, "Cannot connect to reports.zoho.com" + ex.toString());
                return false;
            }
            try {
                loggerObj.log(Level.INFO, "----------------------------------------");
                loggerObj.log(Level.INFO, response.toString());
                response.getStatusLine();
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    loggerObj.log(Level.INFO, "Response content length: " + resEntity.getContentLength());
                    BufferedReader rd = null;
                    try {
                        rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                    } catch (IOException ex) {
                        loggerObj.log(Level.INFO,
                                "cannot read the response 1 from reports.zoho.com" + ex.toString());
                        return false;
                    } catch (UnsupportedOperationException ex) {
                        loggerObj.log(Level.INFO, "cannot read the response 2" + ex.toString());
                        return false;
                    }
                    String line = "";
                    try {
                        loggerObj.log(Level.INFO, "reading response line");
                        while ((line = rd.readLine()) != null) {
                            System.out.println(line);
                            loggerObj.log(Level.INFO, line);
                        }
                    } catch (IOException ex) {
                        loggerObj.log(Level.INFO, "cannot read the response 3" + ex.toString());
                        return false;
                    }
                }
                try {
                    EntityUtils.consume(resEntity);
                } catch (IOException ex) {
                    loggerObj.log(Level.INFO, "cannot read the response 4" + ex.toString());
                    return false;
                }
            } finally {
                try {
                    response.close();
                } catch (IOException ex) {
                    loggerObj.log(Level.INFO, "cannot close the response" + ex.toString());
                    return false;
                }
            }
        } finally {
            try {
                httpclient.close();
            } catch (IOException ex) {
                loggerObj.log(Level.INFO, "cannot read the https clinet" + ex.toString());
                return false;
            }
        }
        return true;
    }
}