Example usage for org.apache.http.impl.client HttpClients createDefault

List of usage examples for org.apache.http.impl.client HttpClients createDefault

Introduction

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

Prototype

public static CloseableHttpClient createDefault() 

Source Link

Document

Creates CloseableHttpClient instance with default configuration.

Usage

From source file:MyTest.DownloadFileTest.java

public static void main(String args[]) {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    String url = "http://www.myexperiment.org/workflows/16/download/Pathways_and_Gene_annotations_for_QTL_region-v7.t2flow?version=7";
    System.out.println(url.charAt(50));
    HttpGet httpget = new HttpGet(url);
    HttpEntity entity = null;//w  w  w. j  a  v  a 2 s.c  om
    try {
        HttpResponse response = httpclient.execute(httpget);
        entity = response.getEntity();
        if (entity != null) {
            InputStream is = entity.getContent();
            String filename = "testdata/Pathways_and_Gene_annotations_for_QTL_region-v7.t2flow";
            BufferedInputStream bis = new BufferedInputStream(is);
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(filename)));
            int readedByte;
            while ((readedByte = bis.read()) != -1) {
                bos.write(readedByte);
            }
            bis.close();
            bos.close();
        }
        httpclient.close();
    } catch (IOException ex) {
        Logger.getLogger(DownloadFileTest.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:hackathon.Hackathon.java

/**
 * @param args the command line arguments
 *///from   w  ww .j ava  2s .c  om
public static void main(String[] args) {
    // TODO code application logic here
    HttpClient httpclient = HttpClients.createDefault();

    try {
        URIBuilder builder = new URIBuilder(
                "https://westus.api.cognitive.microsoft.com/emotion/v1.0/recognize");

        URI uri = builder.build();
        HttpPost request = new HttpPost(uri);
        request.setHeader("Content-Type", "application/json");
        request.setHeader("Ocp-Apim-Subscription-Key", "3532e4ff429c4cce9baa783451db8b3b");

        // Request body
        String url = "https://s-media-cache-ak0.pinimg.com/564x/af/8b/47/af8b47d56ded6952fa8ebfdcf7e87f43.jpg";
        StringEntity reqEntity = new StringEntity(
                "{'url' : 'https://s-media-cache-ak0.pinimg.com/564x/af/8b/47/af8b47d56ded6952fa8ebfdcf7e87f43.jpg'}");
        request.setEntity(reqEntity);

        HttpResponse response = httpclient.execute(request);
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            System.out.println(EntityUtils.toString(entity));
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

From source file:com.javaquery.apache.httpclient.HttpGetExample.java

public static void main(String[] args) {
    /* Create object of CloseableHttpClient */
    CloseableHttpClient httpClient = HttpClients.createDefault();

    /* Prepare get request */
    HttpGet httpGet = new HttpGet("http://www.example.com/api/customer");
    /* Add headers to get request */
    httpGet.addHeader("Authorization", "value");
    httpGet.addHeader("Content-Type", "application/json");

    /* Response handler for after request execution */
    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

        @Override// w  w  w  .  ja v  a  2 s.  c  om
        public String handleResponse(HttpResponse httpResponse) throws ClientProtocolException, IOException {
            /* Get status code */
            int httpResponseCode = httpResponse.getStatusLine().getStatusCode();
            System.out.println("Response code: " + httpResponseCode);
            if (httpResponseCode >= 200 && httpResponseCode < 300) {
                /* Convert response to String */
                HttpEntity entity = httpResponse.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                return null;
                /* throw new ClientProtocolException("Unexpected response status: " + httpResponseCode); */
            }
        }
    };

    try {
        /* Execute URL and attach after execution response handler */
        String strResponse = httpClient.execute(httpGet, responseHandler);
        /* Print the response */
        System.out.println("Response: " + strResponse);
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:chat.parse.ChatParse.java

/**
 * @param args the command line arguments
 *//*from   ww  w  . j a  va  2  s.co  m*/
public static void main(String[] args) throws JSONException, IOException {

    String url = "https://api.parse.com/1/classes/";
    String applicationkey = "RfIUZYQki1tKxFhciTxjD4a712gy1SeY9sw7hhbO";
    String RestApiKey = "WjlZA2VIuonVgd6FKac6tpO8LGztARUHUKFEmeTi";

    CloseableHttpClient client = HttpClients.createDefault();
    HttpPost post = new HttpPost(url + "contatti");

    post.addHeader("Content-Type", "application/json");
    post.addHeader("X-Parse-Application-Id", applicationkey);
    post.addHeader("X-Parse-REST-API-Key", RestApiKey);

    JSONObject obj = new JSONObject();
    obj.put("nome", "Paolo");
    obj.put("surname", "Possanzini");
    obj.put("email", "paolo@teamdev.it");

    post.setEntity(new StringEntity(obj.toString()));

    client.execute(post);

}

From source file:downloadwolkflow.httpTest.java

public final static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*from   w ww .java  2 s. c o  m*/
        HttpGet httpget = new HttpGet(
                "http://www.myexperiment.org/workflows/16/download/Pathways_and_Gene_annotations_for_QTL_region-v7.t2flow?version=7");

        //System.out.println("Executing request " + httpget.getRequestLine());

        // Create a custom response handler
        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

            @Override
            public String handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            }

        };
        String responseBody = httpclient.execute(httpget, responseHandler);
        System.out.println("----------------------------------------");
        System.out.println(responseBody);
    } finally {
        httpclient.close();
    }
}

From source file:com.javaquery.apache.httpclient.HttpDeleteExample.java

public static void main(String[] args) {
    /* Create object of CloseableHttpClient */
    CloseableHttpClient httpClient = HttpClients.createDefault();

    /* Prepare delete request */
    HttpDelete httpDelete = new HttpDelete("http://www.example.com/api/customer");
    /* Add headers to get request */
    httpDelete.addHeader("Authorization", "value");

    /* Response handler for after request execution */
    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

        @Override/*from  w  w w  .  ja va 2  s. c om*/
        public String handleResponse(HttpResponse httpResponse) throws ClientProtocolException, IOException {
            /* Get status code */
            int httpResponseCode = httpResponse.getStatusLine().getStatusCode();
            System.out.println("Response code: " + httpResponseCode);
            if (httpResponseCode >= 200 && httpResponseCode < 300) {
                /* Convert response to String */
                HttpEntity entity = httpResponse.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                return null;
                /* throw new ClientProtocolException("Unexpected response status: " + httpResponseCode); */
            }
        }
    };

    try {
        /* Execute URL and attach after execution response handler */
        String strResponse = httpClient.execute(httpDelete, responseHandler);
        /* Print the response */
        System.out.println("Response: " + strResponse);
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:com.javaquery.apache.httpclient.HttpPutExample.java

public static void main(String[] args) {
    /* Create object of CloseableHttpClient */
    CloseableHttpClient httpClient = HttpClients.createDefault();

    /* Prepare put request */
    HttpPut httpPut = new HttpPut("http://www.example.com/api/customer");
    /* Add headers to get request */
    httpPut.addHeader("Authorization", "value");

    /* Prepare StringEntity from JSON */
    StringEntity jsonData = new StringEntity("{\"id\":\"123\", \"name\":\"Vicky Thakor\"}", "UTF-8");
    /* Body of request */
    httpPut.setEntity(jsonData);/* ww  w  .  ja va2  s  .co  m*/

    /* Response handler for after request execution */
    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

        @Override
        public String handleResponse(HttpResponse httpResponse) throws ClientProtocolException, IOException {
            /* Get status code */
            int httpResponseCode = httpResponse.getStatusLine().getStatusCode();
            System.out.println("Response code: " + httpResponseCode);
            if (httpResponseCode >= 200 && httpResponseCode < 300) {
                /* Convert response to String */
                HttpEntity entity = httpResponse.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                return null;
                /* throw new ClientProtocolException("Unexpected response status: " + httpResponseCode); */
            }
        }
    };

    try {
        /* Execute URL and attach after execution response handler */
        String strResponse = httpClient.execute(httpPut, responseHandler);
        /* Print the response */
        System.out.println("Response: " + strResponse);
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:com.javaquery.apache.httpclient.HttpPostExample.java

public static void main(String[] args) throws UnsupportedEncodingException {
    /* Create object of CloseableHttpClient */
    CloseableHttpClient httpClient = HttpClients.createDefault();

    /* Prepare POST request */
    HttpPost httpPost = new HttpPost("http://www.example.com/api/customer");
    /* Add headers to POST request */
    httpPost.addHeader("Authorization", "value");
    httpPost.addHeader("Content-Type", "application/json");

    /* Prepare StringEntity from JSON */
    StringEntity jsonData = new StringEntity("{\"id\":\"123\", \"name\":\"Vicky Thakor\"}", "UTF-8");
    /* Body of request */
    httpPost.setEntity(jsonData);/*  w  w  w .  j  a v  a 2s.  c o  m*/

    /* Response handler for after request execution */
    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

        @Override
        public String handleResponse(HttpResponse httpResponse) throws ClientProtocolException, IOException {
            /* Get status code */
            int httpResponseCode = httpResponse.getStatusLine().getStatusCode();
            System.out.println("Response code: " + httpResponseCode);
            if (httpResponseCode >= 200 && httpResponseCode < 300) {
                /* Convert response to String */
                HttpEntity entity = httpResponse.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                return null;
                /* throw new ClientProtocolException("Unexpected response status: " + httpResponseCode); */
            }
        }
    };

    try {
        /* Execute URL and attach after execution response handler */
        String strResponse = httpClient.execute(httpPost, responseHandler);
        /* Print the response */
        System.out.println("Response: " + strResponse);
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:com.sim.demo.httpclient.httpget.SinaDemo.java

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

    CloseableHttpClient httpClient = HttpClients.createDefault();
    // HttpGet/* w  w  w. j a  va  2 s  .c o m*/
    HttpGet httpGet = new HttpGet("http://www.sina.com");
    System.out.println("executing request " + httpGet.getURI());
    // get
    HttpResponse response = httpClient.execute(httpGet);
    // ??
    HttpEntity entity = response.getEntity();
    // ???
    System.out.println(response.getStatusLine());
    if (entity != null) {
        // ??
        System.out.println("Response content lenght:" + entity.getContentLength());
        String content = EntityUtils.toString(entity, "UTF-8").trim();
        // HttpClient?? String?
        System.out.println("Response content:" + content);
    }
    // ?
    httpClient.close();
}

From source file:downloadwolkflow.getWorkFlowList.java

public static void main(String args[]) {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    String[] pageList = getPageList();
    System.out.println(pageList.length);
    for (int i = 1; i < pageList.length; i++) {
        System.out.println(pageList[i]);
        System.out.println("---------------------------------------------------------------------------");
        HttpGet httpget = new HttpGet(pageList[i]);
        try {/*  w  w  w  .java  2  s . c  o m*/
            HttpResponse response = httpclient.execute(httpget);
            String page = EntityUtils.toString(response.getEntity());
            Document mainDoc = Jsoup.parse(page);
            Elements resultList = mainDoc.select("div.resource_list_item");
            for (int j = 0; j < resultList.size(); j++) {
                Element workflowResult = resultList.get(j);
                Element detailInfo = workflowResult.select("div.main_panel").first().select("p.title.inline")
                        .first().select("a").first();
                String detailUrl = "http://www.myexperiment.org" + detailInfo.attributes().get("href")
                        + ".html";
                System.out.println(detailUrl);
                downloadWorkFlow(detailUrl, httpclient);
                Thread.sleep(1000);
            }
        } catch (IOException ex) {
            Logger.getLogger(getWorkFlowList.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InterruptedException ex) {
            Logger.getLogger(getWorkFlowList.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    try {
        httpclient.close();
    } catch (IOException ex) {
        Logger.getLogger(getWorkFlowList.class.getName()).log(Level.SEVERE, null, ex);
    }

}