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:TestRESTPost12.java

public static void main(String[] p) throws Exception {
    String strurl = "http://localhost:8080/testnewmaven8/webresources/service/post";

    //StringEntity str=new StringEntity("<a>hello post</a>",ContentType.create("application/xml" , Consts.UTF_8));

    ///*w w w  .java2s  .  c o  m*/
    StringEntity str = new StringEntity("hello post");
    str.setContentType("APPLICATION/xml");

    CloseableHttpClient httpclient = HttpClients.createDefault();

    HttpPost httppost = new HttpPost(strurl);
    httppost.addHeader("Accept", "application/xml charset=UTF-8");
    //httppost.addHeader("content_type", "application/xml, multipart/related");
    httppost.setEntity(str);

    CloseableHttpResponse response = httpclient.execute(httppost);
    // try
    //{
    int statuscode = response.getStatusLine().getStatusCode();
    if (statuscode != 200) {
        System.out.println("http error occured=" + statuscode);
    }

    BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

    while (br.readLine() != null) {
        System.out.println(br.readLine());
    }
    // }
    /*catch(Exception e)
    {
        System.out.println("exception :"+e);
    }*/

    //httpclient.close();

}

From source file:io.github.mikesaelim.arxivoaiharvester.CommandLineInterface.java

public static void main(String[] args) throws InterruptedException {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    ArxivOAIHarvester harvester = new ArxivOAIHarvester(httpClient);
    Scanner scanner = new Scanner(System.in);

    System.out.println();//from w  w w.  j  a v  a2s  . c  o m
    System.out.println("Welcome to the command line interface of the arXiv OAI Harvester!");
    System.out.println(
            "This program sends one query to the arXiv OAI repository and prints the results to STDOUT.");
    System.out.println("It uses the default settings for query retries.");
    System.out.println();
    System.out.println("Which verb would you like to use?");
    System.out.println("    1) GetRecord - retrieve a single record");
    System.out.println("    2) ListRecords - retrieve a range of records");
    System.out.println("    or enter anything else to quit.");

    switch (scanner.nextLine().trim()) {
    case "1":
        handleGetRecordRequest(scanner, harvester);
        break;
    case "2":
        handleListRecordsRequest(scanner, harvester);
    }
}

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

/**
 * @param args/*from   ww  w  . j  av a2s  .  co m*/
 * @throws IOException 
 * @throws ClientProtocolException 
 */
public static void main(String[] args) throws ClientProtocolException, IOException {
    CloseableHttpClient httpClient = HttpClients.createDefault();

    HttpGet httpGet = new HttpGet("http://www.baidu.com");

    System.out.println(httpGet.getURI().toString());

    CloseableHttpResponse response = httpClient.execute(httpGet);

    int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode == 200) {
        HttpEntity entity = response.getEntity();

        String context = EntityUtils.toString(entity, "UTF-8");

        System.out.println("context : " + context);
    }

    httpClient.close();

}

From source file:org.sourcepit.docker.watcher.Main.java

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

    final HttpClientFactory clientFactory = new HttpClientFactory() {
        @Override//from  w w  w  .j  a  v  a  2s . co  m
        public CloseableHttpClient createHttpClient() {
            return HttpClients.createDefault();
        }
    };

    final String dockerDaemonUri = "http://192.168.56.101:2375";
    final String consulAgentUri = "http://192.168.56.101:8500";

    final BlockingQueue<List<JsonObject>> queue = new LinkedBlockingQueue<>();

    final ConsulForwarder consulForwarder = new ConsulForwarder(clientFactory.createHttpClient(),
            consulAgentUri);

    final Thread containerStateDispatcher = new Thread("Consul Forwarder") {
        @Override
        public void run() {
            while (true) {
                try {
                    consulForwarder.forward(queue.take());
                } catch (InterruptedException e) {
                    break;
                } catch (Exception e) {
                    LOG.error("Error while forwarding Docker container state to Consul.", e);
                }
            }
        }
    };
    containerStateDispatcher.start();

    final DockerWatcher watcher = new DockerWatcher(clientFactory, dockerDaemonUri) {
        @Override
        protected void handle(List<JsonObject> containerState) {
            queue.add(containerState);
        }
    };

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            watcher.stop();
            while (containerStateDispatcher.isAlive()) {
                containerStateDispatcher.interrupt();
                try {
                    Thread.sleep(100L);
                } catch (InterruptedException e) {
                }
            }
        }
    });

    watcher.start();
}

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  ww .  j  a  v a  2  s. co  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.ny.apps.executor.httpclient.HttpRequestSender.java

public static void main(String[] args) throws ClientProtocolException, IOException {
    /*/*from  w  w  w  .  jav  a  2s  .c  o  m*/
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope("localhost", 80), new UsernamePasswordCredentials("root", "123"));
    CloseableHttpClient client = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    */
    CloseableHttpClient client = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet("http://www.baidu.com/");
    httpGet.setHeader("Authorization", "");
    logger.info("executing request " + httpGet.getURI());

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

    try {
        String responseBody = client.execute(httpGet, responseHandler);
        System.out.println("----------------------------------------");
        System.out.println(responseBody);
        System.out.println("----------------------------------------");
    } finally {
        client.close();
    }
}

From source file:no.uib.tools.OnthologyHttpClient.java

public static void main(String[] args) {
    try {//w  w  w.  j  ava 2  s  .co m
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet getRequest = new HttpGet(
                "http://www.ebi.ac.uk/ols/api/ontologies/mod/terms/http%253A%252F%252Fpurl.obolibrary.org%252Fobo%252FMOD_00861/descendants?size=2002");
        getRequest.addHeader("accept", "application/json");

        HttpResponse response = httpClient.execute(getRequest);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("Failed to get the PSIMOD onthology : HTTP error code : "
                    + response.getStatusLine().getStatusCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        String output;
        FileWriter fw = new FileWriter("./mod.json");
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
            fw.write(output);
        }

        fw.close();
        httpClient.close();

    } catch (ClientProtocolException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();
    }

}

From source file:de.zazaz.iot.bosch.indego.App.java

public static void main(String[] args) throws ClientProtocolException, IOException, InterruptedException {
    CloseableHttpClient httpClient = HttpClients.createDefault();

    HttpPost httpPost = new HttpPost(BASE_URL_PUSHWOOSH + "registerDevice");
    String jsonPost = ""//
            + "{" //
            + "  \"request\":{" //
            + "     \"application\":\"8FF60-0666B\"," //
            + "     \"push_token\":\"124692134091\"," //
            + "     \"hwid\":\"00-0C-29-E8-B1-8D\"," //
            + "     \"timezone\":3600," //
            + "     \"device_type\":3" //
            + "  }" //
            + "}";
    httpPost.setEntity(new StringEntity(jsonPost, ContentType.APPLICATION_JSON));
    CloseableHttpResponse response = httpClient.execute(httpPost);

    System.out.println(response.getStatusLine());
    Header[] headers = response.getAllHeaders();
    for (int i = 0; i < headers.length; i++) {
        System.out.println(headers[i].getName() + ": " + headers[i].getValue());
    }/*from   w ww  .ja  v  a  2s.c o  m*/
    HttpEntity entity = response.getEntity();
    String contents = EntityUtils.toString(entity);
    System.out.println(contents);

    Thread.sleep(5000);

    HttpPost httpGet = new HttpPost(BASE_URL_PUSHWOOSH + "checkMessage");
    String jsonGet = ""//
            + "{" //
            + "  \"request\":{" //
            + "     \"application\":\"8FF60-0666B\"," //
            + "     \"hwid\":\"00-0C-29-E8-B1-8D\"" //
            + "  }" //
            + "}";
    httpGet.setEntity(new StringEntity(jsonGet, ContentType.APPLICATION_JSON));
    httpClient.execute(httpGet);

    response.close();
}

From source file:demo.example.ClientAbortMethod.java

public final static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*w  w  w .j a v  a 2  s. c o  m*/
        HttpGet httpget = new HttpGet("http://httpbin.org/get");

        System.out.println("Executing request " + httpget.getURI());
        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            // Do not feel like reading the response body
            // Call abort on the request object
            httpget.abort();
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:com.lxf.spider.client.ClientAbortMethod.java

public final static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {// ww  w .j  a  va  2  s .  c  om
        HttpGet httpget = new HttpGet("http://www.apache.org/");

        System.out.println("Executing request " + httpget.getURI());
        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            // Do not feel like reading the response body
            // Call abort on the request object
            httpget.abort();
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}