Example usage for org.apache.http.impl.client CloseableHttpClient execute

List of usage examples for org.apache.http.impl.client CloseableHttpClient execute

Introduction

In this page you can find the example usage for org.apache.http.impl.client CloseableHttpClient execute.

Prototype

public CloseableHttpResponse execute(final HttpUriRequest request) throws IOException, ClientProtocolException 

Source Link

Usage

From source file:ClientChunkEncodedPost.java

public static void main(String[] args) throws Exception {
    if (args.length != 1) {
        System.out.println("File path not given");
        System.exit(1);/*from   w w w  .  jav  a  2  s  .c om*/
    }
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpPost httppost = new HttpPost("http://localhost/");

        File file = new File(args[0]);

        InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1,
                ContentType.APPLICATION_OCTET_STREAM);
        reqEntity.setChunked(true);
        // It may be more appropriate to use FileEntity class in this particular
        // instance but we are using a more generic InputStreamEntity to demonstrate
        // the capability to stream out data from any arbitrary source
        //
        // FileEntity entity = new FileEntity(file, "binary/octet-stream");

        httppost.setEntity(reqEntity);

        System.out.println("Executing request: " + httppost.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            EntityUtils.consume(response.getEntity());
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:demo.example.ClientChunkEncodedPost.java

public static void main(String[] args) throws Exception {
    if (args.length != 1) {
        System.out.println("File path not given");
        System.exit(1);/*from  w ww. j a va 2s  .c o m*/
    }
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpPost httppost = new HttpPost("http://httpbin.org/post");

        File file = new File(args[0]);

        InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1,
                ContentType.APPLICATION_OCTET_STREAM);
        reqEntity.setChunked(true);
        // It may be more appropriate to use FileEntity class in this particular
        // instance but we are using a more generic InputStreamEntity to demonstrate
        // the capability to stream out data from any arbitrary source
        //
        // FileEntity entity = new FileEntity(file, "binary/octet-stream");

        httppost.setEntity(reqEntity);

        System.out.println("Executing request: " + httppost.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            System.out.println(EntityUtils.toString(response.getEntity()));
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:com.wolfsoftco.httpclient.RestClient.java

@SuppressWarnings("resource")
public static void main(String[] args) {
    CloseableHttpClient httpclient = null;
    CloseableHttpResponse response = null;
    try {// w  ww.ja va2 s  . c om
        HttpEntity entity = null;
        String responseHtml = null;
        httpclient = HttpClients.custom().build();

        //Based on CURL line:
        //curl localhost:9090/oauth/token -d "grant_type=password&scope=write&username=greg&password=turnquist" -u foo:bar

        //clientid:secret
        String clientID = "foo:bar";

        HttpUriRequest login = RequestBuilder.post().setUri(new URI(URL))
                .addHeader("Authorization", "Basic " + Base64.encodeBase64String(clientID.getBytes()))
                .addParameter("grant_type", "password").addParameter("scope", "read")
                .addParameter("username", "greg").addParameter("password", "turnquist").build();

        response = httpclient.execute(login);
        entity = response.getEntity();

        responseHtml = EntityUtils.toString(entity);
        EntityUtils.consume(entity);

        JsonObject jsonObject = null;
        String token = null;
        if (responseHtml.startsWith("{")) {
            JsonParser parser = new JsonParser();
            jsonObject = parser.parse(responseHtml).getAsJsonObject();
            token = jsonObject.get("access_token").getAsString();
        }

        if (token != null) {
            HttpGet request = new HttpGet(URL_FLIGHTS);
            request.addHeader("Authorization", "Bearer " + token);

            response = httpclient.execute(request);
            entity = response.getEntity();
            responseHtml = EntityUtils.toString(entity);
            EntityUtils.consume(entity);
            System.out.println(responseHtml);

        }

    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        try {

            if (httpclient != null)
                httpclient.close();
            if (response != null)
                response.close();

        } catch (IOException e) {
        }
    }
}

From source file:httpclientdemo.ClientChunkEncodedPost.java

public static void main(String[] args) throws Exception {
    //        if (args.length != 1)  {
    //            System.out.println("File path not given");
    //            System.exit(1);
    //        }/*from w  w  w.  j ava  2  s  .  co  m*/
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpPost httppost = new HttpPost("http://httpbin.org/post");

        File file = new File("/Users/jack/Downloads/listdata (1).xlsx");

        InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1,
                ContentType.APPLICATION_OCTET_STREAM);
        reqEntity.setChunked(true);
        // It may be more appropriate to use FileEntity class in this particular
        // instance but we are using a more generic InputStreamEntity to demonstrate
        // the capability to stream out data from any arbitrary source
        //
        // FileEntity entity = new FileEntity(file, "binary/octet-stream");

        httppost.setEntity(reqEntity);

        System.out.println("Executing request: " + httppost.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            System.out.println(EntityUtils.toString(response.getEntity()));
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:pt.ua.tm.neji.web.test.TestREST.java

public static void main(String[] args) throws IOException, KeyStoreException, NoSuchAlgorithmException,
        CertificateException, KeyManagementException, UnrecoverableKeyException {

    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    trustStore.load(null, null);/*from  ww  w. j  a  va  2  s . c  om*/

    MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
    sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "utf-8");

    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    registry.register(new Scheme("https", sf, 8010));

    ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

    String url = "https://localhost:8010/annotate/default/export?tool=becas-webapp&email=bioinformatics@ua.pt";

    // POST
    CloseableHttpClient client = new DefaultHttpClient(ccm, params);

    HttpPost post = new HttpPost(url);
    //post.setHeader("Content-Type", "application/json");

    List<NameValuePair> keyValuesPairs = new ArrayList();
    //keyValuesPairs.add(new BasicNameValuePair("format", "neji"));
    keyValuesPairs.add(new BasicNameValuePair("fromFile", "false"));
    //keyValuesPairs.add(new BasicNameValuePair("groups", "{\"DISO\":true,\"ANAT\":true}"));
    //keyValuesPairs.add(new BasicNameValuePair("groups", "{}"));
    //keyValuesPairs.add(new BasicNameValuePair("groups", "{\"DISO\":true}"));
    //keyValuesPairs.add(new BasicNameValuePair("groups", "{\"ANAT\":true}"));
    keyValuesPairs.add(new BasicNameValuePair("text", text));
    keyValuesPairs.add(new BasicNameValuePair("crlf", "false"));
    post.setEntity(new UrlEncodedFormEntity(keyValuesPairs));

    HttpResponse response = client.execute(post);

    String result = IOUtils.toString(response.getEntity().getContent());

    System.out.println(result);
}

From source file:org.camunda.bpm.RestDeployment.java

public static void main(String[] args) throws IOException {
    if (args.length == 0) {
        System.err.println("No process files specified");
        System.exit(1);//  w  w w  . j  a  va  2 s . c o m
    }

    CloseableHttpClient httpClient = HttpClients.createDefault();

    HttpPost httpPost = new HttpPost("http://localhost:8080/engine-rest/deployment/create");

    StringBody deploymentName = new StringBody("myDeployment", ContentType.TEXT_PLAIN);
    StringBody enableDuplicateFiltering = new StringBody("true", ContentType.TEXT_PLAIN);
    StringBody deployChangedOnly = new StringBody("true", ContentType.TEXT_PLAIN);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create().addPart("deployment-name", deploymentName)
            .addPart("enable-duplicate-filtering", enableDuplicateFiltering)
            .addPart("deploy-changed-only", deployChangedOnly);

    for (String resource : args) {
        File resourceFile = new File(resource);
        FileBody fileBody = new FileBody(resourceFile);
        builder.addPart(resourceFile.getName(), fileBody);
    }

    HttpEntity httpEntity = builder.build();
    httpPost.setEntity(httpEntity);

    HttpResponse response = httpClient.execute(httpPost);

    logResponse(response);
}

From source file:com.lexmark.saperion.util.ClientMultipartFormPost.java

public static void main(String[] args) throws Exception {
    String userName = "amolugu";
    String password = "ecm";
    String authString = userName + ":" + password;
    byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
    String authStringEnc = new String(authEncBytes);
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*from w ww .  j av  a  2 s.  com*/
        HttpPost httpPost = new HttpPost("https://ecm-service.psft.co/ecms/documents");

        //http
        httpPost.addHeader("Authorization", "Basic " + authStringEnc);
        httpPost.addHeader("Accept", "application/json");
        httpPost.addHeader("saTenant", "india");
        httpPost.addHeader("saLicense", "1");
        httpPost.addHeader("Content-Type", "application/octet-stream");

        FileBody bin = new FileBody(new File("C:\\Users\\Aditya.Molugu\\workspace\\RestClient\\Binaries.txt"));
        StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);

        HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment)
                .build();

        //HttpBo
        httpPost.setEntity(reqEntity);

        System.out.println("executing request " + httpPost.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httpPost);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                System.out.println("Response content length: " + resEntity.getContentLength());
            }
            EntityUtils.consume(resEntity);
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:net.cloudkit.relaxation.HttpClientTest.java

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

    InetAddress[] addresss = InetAddress.getAllByName("google.com");
    for (InetAddress address : addresss) {

        System.out.println(address);

    }/*from  w ww. j a  va 2 s  .c o  m*/

    CloseableHttpClient httpclient = HttpClients.createDefault();

    String __VIEWSTATE = "";
    String __EVENTVALIDATION = "";

    HttpGet httpGet = new HttpGet("http://query.customs.gov.cn/MNFTQ/MRoadQuery.aspx?" + Math.random() * 1000);
    httpGet.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
    httpGet.setHeader("Accept-Encoding", "gzip, deflate, sdch");
    httpGet.setHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
    httpGet.setHeader("Cache-Control", "no-cache");
    // httpGet.setHeader("Connection", "keep-alive");
    httpGet.setHeader("Host", "query.customs.gov.cn");
    httpGet.setHeader("Pragma", "no-cache");
    httpGet.setHeader("Upgrade-Insecure-Requests", "1");
    httpGet.setHeader("User-Agent",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36");

    HttpClientContext context = HttpClientContext.create();
    // CloseableHttpResponse response1 = httpclient.execute(httpGet, context);
    CloseableHttpResponse response1 = httpclient.execute(httpGet);
    // Header[] headers = response1.getHeaders(HttpHeaders.CONTENT_TYPE);
    // System.out.println("context cookies:" + context.getCookieStore().getCookies());
    // String setCookie = response1.getFirstHeader("Set-Cookie").getValue();
    // System.out.println("context cookies:" + setCookie);

    try {
        System.out.println(response1.getStatusLine());
        HttpEntity entity1 = response1.getEntity();
        // do something useful with the response body and ensure it is fully consumed

        String result = IOUtils.toString(entity1.getContent(), "GBK");
        // System.out.println(result);

        Matcher m1 = Pattern.compile(
                "<input type=\\\"hidden\\\" name=\\\"__VIEWSTATE\\\" id=\\\"__VIEWSTATE\\\" value=\\\"(.*)\\\" />")
                .matcher(result);
        __VIEWSTATE = m1.find() ? m1.group(1) : "";
        Matcher m2 = Pattern.compile(
                "<input type=\\\"hidden\\\" name=\\\"__EVENTVALIDATION\\\" id=\\\"__EVENTVALIDATION\\\" value=\\\"(.*)\\\" />")
                .matcher(result);
        __EVENTVALIDATION = m2.find() ? m2.group(1) : "";

        System.out.println(__VIEWSTATE);
        System.out.println(__EVENTVALIDATION);

        /*
        File storeFile = new File("D:\\customs\\customs"+ i +".jpg");
        FileOutputStream output = new FileOutputStream(storeFile);
        IOUtils.copy(input, output);
        output.close();
        */
        EntityUtils.consume(entity1);
    } finally {
        response1.close();
    }

    HttpPost httpPost = new HttpPost(
            "http://query.customs.gov.cn/MNFTQ/MRoadQuery.aspx?" + Math.random() * 1000);
    httpPost.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
    httpPost.setHeader("Accept-Encoding", "gzip, deflate");
    httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
    httpPost.setHeader("Cache-Control", "no-cache");
    // httpPost.setHeader("Connection", "keep-alive");
    httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
    httpPost.setHeader("Cookie", "ASP.NET_SessionId=t1td453hcuy4oqiplekkqe55");
    httpPost.setHeader("Host", "query.customs.gov.cn");
    httpPost.setHeader("Origin", "http://query.customs.gov.cn");
    httpPost.setHeader("Pragma", "no-cache");
    httpPost.setHeader("Referer", "http://query.customs.gov.cn/MNFTQ/MRoadQuery.aspx");
    httpPost.setHeader("Upgrade-Insecure-Requests", "1");
    httpPost.setHeader("User-Agent",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36");

    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("__VIEWSTATE", __VIEWSTATE));
    nvps.add(new BasicNameValuePair("__EVENTVALIDATION", __EVENTVALIDATION));
    nvps.add(new BasicNameValuePair("ScrollTop", ""));
    nvps.add(new BasicNameValuePair("__essVariable", ""));
    nvps.add(new BasicNameValuePair("MRoadQueryCtrl1$txtManifestID", "5100312462240"));
    nvps.add(new BasicNameValuePair("MRoadQueryCtrl1$txtBillNo", "7PH650021105"));
    nvps.add(new BasicNameValuePair("MRoadQueryCtrl1$txtCode", "a778"));
    nvps.add(new BasicNameValuePair("MRoadQueryCtrl1$btQuery", "   "));
    nvps.add(new BasicNameValuePair("select", ""));
    nvps.add(new BasicNameValuePair("select1", ""));
    nvps.add(new BasicNameValuePair("select2", ""));
    nvps.add(new BasicNameValuePair("select3", ""));
    nvps.add(new BasicNameValuePair("select4", ""));
    nvps.add(new BasicNameValuePair("select5", "??"));
    nvps.add(new BasicNameValuePair("select6", ""));
    nvps.add(new BasicNameValuePair("select7", ""));
    nvps.add(new BasicNameValuePair("select8", ""));

    httpPost.setEntity(new UrlEncodedFormEntity(nvps, "GBK"));

    CloseableHttpResponse response2 = httpclient.execute(httpPost);

    try {
        System.out.println(response2.getStatusLine());
        HttpEntity entity2 = response2.getEntity();
        // do something useful with the response body
        // and ensure it is fully consumed
        // System.out.println(entity2.getContent());
        System.out.println(IOUtils.toString(response2.getEntity().getContent(), "GBK"));

        EntityUtils.consume(entity2);
    } finally {
        response2.close();
    }

}

From source file:com.http.my.ClientFormLogin.java

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

    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

        public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
            int status = response.getStatusLine().getStatusCode();
            System.out.println(response.getStatusLine());
            if (status >= 200 && status < 303) {
                HttpEntity entity = response.getEntity();

                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                throw new ClientProtocolException("Unexpected response status: " + status);
            }/*from  w w  w .  j av  a2  s . c om*/
        }

    };

    BasicCookieStore cookieStore = new BasicCookieStore();
    //        
    //        BasicClientCookie cookieJSESSIONID = new BasicClientCookie("JSESSIONID", "3FD927DC6911B719E4492E7473897FBA");
    //        cookieJSESSIONID.setVersion(0);
    //        cookieJSESSIONID.setDomain("218.75.79.230");
    //        cookieJSESSIONID.setPath("/");
    //        System.out.println("Initial set of cookies:");
    //        cookieStore.addCookie(cookieJSESSIONID);

    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
    // HttpProtocolParams.setUserAgent(httpclient.getParams(), "Mozilla/5.0 (Windows; U; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)");

    try {

        // HttpPost httpost = new HttpPost("http://localhost:8081/cring/jsp/user/userLogin.do?method=login");
        HttpPost loginpost = new HttpPost("http://134.96.41.47/ecommunications_chs/start.swe");
        //HttpGet loginGet = new HttpGet("http://134.96.41.47/ecommunications_chs/start.swe");
        // HttpGet loginGet = new HttpGet("http://www.baidu.com");
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("SWEUserName", "nili"));
        nvps.add(new BasicNameValuePair("SWEPassword", "nili7788"));
        nvps.add(new BasicNameValuePair("SWEFo", "SWEEntryForm"));
        nvps.add(new BasicNameValuePair("SWENeedContext", "false"));
        nvps.add(new BasicNameValuePair("SWECmd", "ExecuteLogin"));
        nvps.add(new BasicNameValuePair("W", "t"));
        nvps.add(new BasicNameValuePair("SWEC", "0"));
        nvps.add(new BasicNameValuePair("SWEBID", "-1"));
        nvps.add(new BasicNameValuePair("SWETS", "1385712482625"));

        /**
         *  SWEUserName:111111
        SWEPassword:222222
        SWEFo:SWEEntryForm
        SWENeedContext:false
        SWECmd:ExecuteLogin
        W:t
        SWESPNR:
        SWESPNH:
        SWEH:
        SWEC:0
        SWEW:
        SWEBID:-1
        SWETS:1385712482625
        SWEWN:
         */
        loginpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
        //            CloseableHttpResponse response =  httpclient.execute(loginpost);
        // HttpEntity httpEntity =  response.getEntity();
        CloseableHttpResponse responseGet = httpclient.execute(loginpost);
        HttpEntity httpEntityGet = responseGet.getEntity();
        System.out.println("statusLine: " + responseGet.getStatusLine());
        System.out.println("ContentType: " + httpEntityGet.getContentType());
        System.out.println("ContentLength: " + httpEntityGet.getContentLength());

        //  httpEntityGet.get
        System.out.println("loginGet: " + EntityUtils.toString(httpEntityGet));
        /* try {
                
        System.out.println("Post logon cookies:");
        List<Cookie> cookies = cookieStore.getCookies();
        if (cookies.isEmpty()) {
            System.out.println("None");
        } else {
            for (int i = 0; i < cookies.size(); i++) {
                System.out.println("- " + cookies.get(i).toString());
            }
        }
                
                
                
        HttpPost modifypost = new HttpPost("http://localhost:8081/cring/jsp/user/corpUserController.do?method=modifyPwd");
        List <NameValuePair> modifynvps = new ArrayList <NameValuePair>();
        modifynvps.add(new BasicNameValuePair("newPwd","111111"));
        modifypost.setEntity(new UrlEncodedFormEntity(modifynvps, Consts.UTF_8));
                    
        CloseableHttpResponse modifyresponse = httpclient.execute(modifypost);
            System.out.println("modifyresponse : "+modifyresponse.getStatusLine()); 
                
                
                
         } finally {
        //response2.close();
         }*/
    } finally {
        httpclient.close();
    }
}

From source file:client.QueryLastFm.java

License:asdf

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

    // isAlreadyInserted("asdfs","jas,jnjkah");

    // FileWriter fw = new FileWriter(".\\tracks.csv");
    OutputStream track_os = new FileOutputStream(".\\tracks.csv");
    PrintWriter out = new PrintWriter(new OutputStreamWriter(track_os, "UTF-8"));

    OutputStream track_id_os = new FileOutputStream(".\\track_id_sim_track_id.csv");
    PrintWriter track_id_out = new PrintWriter(new OutputStreamWriter(track_id_os, "UTF-8"));

    track_id_out.print("");

    ByteArrayInputStream input;/* w  ww . j a va2  s . c  o m*/
    Document doc = null;
    CloseableHttpClient httpclient = HttpClients.createDefault();

    String trackName = "";
    String artistName = "";
    String sourceMbid = "";
    out.print("ID");// first row first column
    out.print(",");
    out.print("TrackName");// first row second column
    out.print(",");
    out.println("Artist");// first row third column

    track_id_out.print("source");// first row second column
    track_id_out.print(",");
    track_id_out.println("target");// first row third column
    // track_id_out.print(",");
    // track_id_out.println("type");// first row third column

    // out.flush();

    // out.close();

    // fw.close();

    // os.close();

    try {
        URI uri = new URIBuilder().setScheme("http").setHost("ws.audioscrobbler.com").setPath("/2.0/")
                .setParameter("method", "track.getsimilar").setParameter("artist", "cher")
                .setParameter("track", "believe").setParameter("limit", "100")
                .setParameter("api_key", "88858618961414f8bec919bddd057044").build();

        // new URIBuilder().
        HttpGet request = new HttpGet(uri);

        // request.
        // This is useful for last.fm logging and preventing them from blocking this client
        request.setHeader(HttpHeaders.USER_AGENT,
                "nileshmore@gatech.edu - ClassAssignment at GeorgiaTech Non-commercial use");

        HttpGet httpGet = new HttpGet(
                "http://ws.audioscrobbler.com/2.0/?method=track.getsimilar&artist=cher&track=believe&limit=4&api_key=88858618961414f8bec919bddd057044");
        CloseableHttpResponse response = httpclient.execute(request);

        int statusCode = response.getStatusLine().getStatusCode();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        // The underlying HTTP connection is still held by the response object
        // to allow the response content to be streamed directly from the network socket.
        // In order to ensure correct deallocation of system resources
        // the user MUST call CloseableHttpResponse#close() from a finally clause.
        // Please note that if response content is not fully consumed the underlying
        // connection cannot be safely re-used and will be shut down and discarded
        // by the connection manager.
        try {
            if (statusCode == 200) {
                HttpEntity entity1 = response.getEntity();
                BufferedReader br = new BufferedReader(
                        new InputStreamReader((response.getEntity().getContent())));
                Document document = builder.parse((response.getEntity().getContent()));
                Element root = document.getDocumentElement();
                root.normalize();
                // Need to focus and resolve this part
                NodeList nodes;
                nodes = root.getChildNodes();

                nodes = root.getElementsByTagName("track");
                if (nodes.getLength() == 0) {
                    // System.out.println("empty");
                    return;
                }
                Node trackNode;
                for (int k = 0; k < nodes.getLength(); k++) // can access all tracks now
                {
                    trackNode = nodes.item(k);
                    NodeList trackAttributes = trackNode.getChildNodes();

                    // check if mbid is present in track attributes
                    // System.out.println("Length  " + (trackAttributes.item(5).getNodeName().compareToIgnoreCase("mbid") == 0));

                    if ((trackAttributes.item(5).getNodeName().compareToIgnoreCase("mbid") == 0)) {
                        if (((Element) trackAttributes.item(5)).hasChildNodes())
                            ;// System.out.println("Go aHead");
                        else
                            continue;
                    } else
                        continue;

                    for (int n = 0; n < trackAttributes.getLength(); n++) {
                        Node attribute = trackAttributes.item(n);
                        if ((attribute.getNodeName().compareToIgnoreCase("name")) == 0) {
                            // System.out.println(((Element)attribute).getFirstChild().getNodeValue());
                            trackName = ((Element) attribute).getFirstChild().getNodeValue(); // make string encoding as UTF-8 ************ 

                        }

                        if ((attribute.getNodeName().compareToIgnoreCase("mbid")) == 0) {
                            // System.out.println(n +  "   " +  ((Element)attribute).getFirstChild().getNodeValue());
                            sourceMbid = attribute.getFirstChild().getNodeValue();

                        }

                        if ((attribute.getNodeName().compareToIgnoreCase("artist")) == 0) {
                            NodeList ArtistNodeList = attribute.getChildNodes();
                            for (int j = 0; j < ArtistNodeList.getLength(); j++) {
                                Node Artistnode = ArtistNodeList.item(j);
                                if ((Artistnode.getNodeName().compareToIgnoreCase("name")) == 0) {
                                    // System.out.println(((Element)Artistnode).getFirstChild().getNodeValue());
                                    artistName = ((Element) Artistnode).getFirstChild().getNodeValue();
                                }
                            }
                        }
                    }
                    out.print(sourceMbid);
                    out.print(",");
                    out.print(trackName);
                    out.print(",");
                    out.println(artistName);
                    // out.print(",");
                    findSimilarTracks(track_id_out, sourceMbid, trackName, artistName);

                }
                track_id_out.flush();

                out.flush();
                out.close();
                track_id_out.close();
                track_os.close();

                // fw.close();
                Element trac = (Element) nodes.item(0);
                // trac.normalize();
                nodes = trac.getChildNodes();
                // System.out.println(nodes.getLength());

                for (int i = 0; i < nodes.getLength(); i++) {
                    Node node = nodes.item(i);
                    // System.out.println(node.getNodeName());
                    if ((node.getNodeName().compareToIgnoreCase("name")) == 0) {
                        // System.out.println(((Element)node).getFirstChild().getNodeValue());
                    }

                    if ((node.getNodeName().compareToIgnoreCase("mbid")) == 0) {
                        // System.out.println(((Element)node).getFirstChild().getNodeValue());
                    }

                    if ((node.getNodeName().compareToIgnoreCase("artist")) == 0) {

                        // System.out.println("Well");
                        NodeList ArtistNodeList = node.getChildNodes();
                        for (int j = 0; j < ArtistNodeList.getLength(); j++) {
                            Node Artistnode = ArtistNodeList.item(j);
                            if ((Artistnode.getNodeName().compareToIgnoreCase("name")) == 0) {
                                /* System.out.println(((Element)Artistnode).getFirstChild().getNodeValue());*/
                            }
                            /*System.out.println(Artistnode.getNodeName());*/
                        }
                    }

                }
                /*if(node instanceof Element){
                  //a child element to process
                  Element child = (Element) node;
                  String attribute = child.getAttribute("width");
                }*/

                // System.out.println(root.getAttribute("status"));
                NodeList tracks = root.getElementsByTagName("track");
                Element track = (Element) tracks.item(0);
                // System.out.println(track.getTagName());
                track.getChildNodes();

            } else {
                System.out.println("failed with status" + response.getStatusLine());
            }
            // input = (ByteArrayInputStream)entity1.getContent();
            // do something useful with the response body
            // and ensure it is fully consumed
        } finally {
            response.close();
        }
    }

    finally {
        System.out.println("Exited succesfully.");
        httpclient.close();

    }
}