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:com.vmware.identity.rest.core.client.BaseClient.java

/**
 * Constructs a client with a {@code host}. This will use the default
 * {@link HttpClient} and a {@link SimpleHostRetriever}. The port is assumed to be
 * the default port (-1)./*from   ww  w  .ja  v  a 2 s  .  c om*/
 *
 * @see HttpClients#createDefault()
 * @param host the hostname of the remote REST server.
 */
protected BaseClient(String host) {
    this(new SimpleHostRetriever(host), HttpClients.createDefault());
}

From source file:org.assertdevelopments.promise.poc.client.StreamClient.java

public StreamClient() {
    this.httpClient = HttpClients.createDefault();
}

From source file:linkipedia.EsorService.java

private static List<ConceptItem> lookupEsor(QueryItem queryItem) throws Exception {

    HttpClient client = HttpClients.createDefault();
    String uriStr = REST_URL + "?query=" + queryItem.toString();
    //System.out.println(uriStr);

    HttpGet method = new HttpGet(uriStr);
    method.setHeader("Accept", "application/json");
    HttpResponse response = client.execute(method);
    int code = response.getStatusLine().getStatusCode();
    if (2 != code / 100) {
        throw new Exception("response code " + code + " for resource at " + uriStr);
    }/*from   w  ww. j  av  a2  s .  co m*/
    InputStream body = response.getEntity().getContent();
    String jsonStr = convertStreamToString(body);
    //System.out.println(jsonStr);

    JSONObject json = new JSONObject(jsonStr);
    String query = json.getString("query");
    JSONArray results = json.getJSONArray("results");

    //analysis the result and return
    ArrayList<ConceptItem> concepts = new ArrayList<ConceptItem>();
    for (int i = 0; i < results.length(); i++) {
        JSONObject r = results.getJSONObject(i);
        String url = r.getString("url");
        String score = r.getString("score");

        if (url.length() > 0) {
            if (url.contains("http")) {
                ConceptItem c = new ConceptItem(new URI(url.substring(1, url.length() - 1)),
                        Double.parseDouble(score));
                concepts.add(c);
            }
        } else {
            //System.out.println(queryItem+":NA");
        }
    }

    return concepts;
}

From source file:org.jboss.integration.fuse.camel.test.KieCamelJbpmWorkitemsQuickstartTest.java

@Test
public void test() throws Exception {
    int port = 8080;

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet("http://localhost:" + port + "/jbpm-workitems-camel/mortgage");
    CloseableHttpResponse response = httpclient.execute(httpGet);
    try {/*  w  ww . java  2 s  . co  m*/
        System.out.println(response.getStatusLine());
        assertTrue(response.getStatusLine().getStatusCode() == 200);
        HttpEntity entity1 = response.getEntity();
        // do something useful with the response body
        // and ensure it is fully consumed
        StringWriter writer = new StringWriter();
        IOUtils.copy(entity1.getContent(), writer);
        String content = writer.toString();
        System.out.println("RESPONSE:\n" + content);
        assertTrue(content.contains("Accepted Applications"));
        assertTrue(content.contains("Rejected Applications"));

    } finally {
        response.close();
    }
}

From source file:org.stem.api.BaseHttpClient.java

public BaseHttpClient(String uri) {
    try {/*ww  w.  j ava 2  s. c  om*/
        this.root = new URI(uri);
        client = HttpClients.createDefault();
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
}

From source file:nl.salp.warcraft4j.io.CachedHttpDataReader.java

/**
 * Read the data from a file (direct blocking http read).
 *
 * @param url The URL of the file to read.
 *
 * @return The file contents.//from w  w w .  j  a  va  2 s  . c om
 *
 * @throws DataReadingException When reading the file failed.
 */
private static byte[] getData(String url) throws DataReadingException {
    try (CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse response = httpClient.execute(new HttpGet(URI.create(url)))) {
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() > 300) {
            throw new DataReadingException(String.format("Error opening HTTP data reader for %s: error %d: %s",
                    url, statusLine.getStatusCode(), statusLine.getReasonPhrase()));
        }
        HttpEntity entity = response.getEntity();
        if (entity == null) {
            throw new DataReadingException(format("HTTP data reader received no response from for %s", url));
        }
        byte[] data = EntityUtils.toByteArray(entity);
        EntityUtils.consume(entity);
        return data;
    } catch (IOException e) {
        throw new DataReadingException(e);
    }
}

From source file:com.lenovo.h2000.services.LicenseServiceImpl.java

@Override
public String upload(String filePath, Map<String, String> headers) throws Exception {
    _logger.info("calling LicenseServiceImpl.upload function");
    Map<String, String> params = new HashMap<String, String>();

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(
            HttpConfig.parseBaseUrl(headers) + "license/import" + "?" + TypeUtil.mapToString(params));// new HttpPost("http://localhost:3002/license/import");

    String responseBody = "";
    DataInputStream in = null;//from  w  w  w. j av  a 2 s  .c  om
    try {
        _logger.info("filePath" + filePath);
        File file = new File(filePath);
        in = new DataInputStream(new FileInputStream(filePath));
        byte[] bufferOut = new byte[(int) file.length()];

        int bytes = 0;
        int i = 0;
        int len = (int) (1024 > file.length() ? file.length() : 1024);
        while ((bytes = in.read(bufferOut, i, len)) > 0) {
            if (bytes < 1024)
                break;
            else {
                len = (int) (file.length() - bytes);
                i += bytes;
            }
        }

        ByteArrayEntity requestEntity = new ByteArrayEntity(bufferOut);
        requestEntity.setContentEncoding("UTF-8");
        requestEntity.setContentType("application/octet-stream");
        httpPost.setEntity(requestEntity);
        HttpResponse response = httpClient.execute(httpPost);
        response.setHeader(HttpHeaders.CONTENT_TYPE, "application/json; charset=UTF-8");
        HttpEntity responseEntity = response.getEntity();
        responseBody = EntityUtils.toString(responseEntity);

        if (file.isFile() && file.exists()) {
            file.delete();
        }

    } catch (ClientProtocolException e) {
        e.printStackTrace();
        _logger.error("throwing HttpClientUtil.doPost ClientProtocolException with " + e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        _logger.error("throwing HttpClientUtil.doPost IOException with " + e.getMessage());
    } finally {
        httpClient.close();
        if (in != null) {
            in.close();
        }
    }
    return responseBody;
}

From source file:com.fufang.testcase.orgmanager.orgm.GetGspLicense.java

@Test
public void getGspLicense() throws ClientProtocolException, IOException, URISyntaxException {
    String cookie = getCookie();/*from   w  w w.j  av a 2 s  . co m*/
    CloseableHttpClient httpClient = HttpClients.createDefault();
    CloseableHttpResponse response = null;
    InputStream is = null;
    String url = "http://172.16.88.183:9999/organization-manager/orgManager/getGspLicense";
    try {
        HttpGet httpGet = new HttpGet(url);
        httpGet.addHeader("cookie", cookie);
        response = httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            is = entity.getContent();
            //??  
            BufferedReader br = new BufferedReader(new InputStreamReader(is, Consts.UTF_8));
            String result = null;
            while ((result = br.readLine()) != null) {
                System.out.println(result);

                JSONObject jsonObject = JSONObject.fromObject(result);

                JSONArray rowsArray = jsonObject.getJSONArray("rows");
                System.out.println(rowsArray);

                int gspType;
                List<Integer> gspTypeList = new ArrayList<Integer>();
                gspTypeList.add(0);
                gspTypeList.add(0);
                gspTypeList.add(0);
                gspTypeList.add(0);

                int licenseType;
                List<Integer> licenseTypeList = new ArrayList<Integer>();
                licenseTypeList.add(0);
                licenseTypeList.add(0);
                licenseTypeList.add(0);
                licenseTypeList.add(1);

                String description;
                List<String> descriptionList = new ArrayList<String>();
                descriptionList.add("?");
                descriptionList.add("??");
                descriptionList.add("??");
                descriptionList.add("?");

                String gspTypeName;
                List<String> gspTypeNameList = new ArrayList<String>();
                gspTypeNameList.add("?");
                gspTypeNameList.add("?");
                gspTypeNameList.add("?");
                gspTypeNameList.add("?");

                String licenseTypeName;
                List<String> licenseTypeNameList = new ArrayList<String>();
                licenseTypeNameList.add("?");
                licenseTypeNameList.add("?");
                licenseTypeNameList.add("?");
                licenseTypeNameList.add("");

                for (int i = 0; i < 4; i++) {
                    gspType = rowsArray.getJSONObject(i).getInt("gspType");
                    licenseType = rowsArray.getJSONObject(i).getInt("licenseType");
                    description = rowsArray.getJSONObject(i).getString("description");
                    gspTypeName = rowsArray.getJSONObject(i).getString("gspTypeName");
                    licenseTypeName = rowsArray.getJSONObject(i).getString("licenseTypeName");

                    int expectgspType = gspTypeList.get(i);
                    int expectLicenseType = licenseTypeList.get(i);
                    String expectDescription = descriptionList.get(i);
                    String expectgspTypeName = gspTypeNameList.get(i);
                    String expcetLicenseTypeName = licenseTypeNameList.get(i);

                    Assert.assertEquals(gspType, expectgspType, "wrong gspType");
                    Assert.assertEquals(licenseType, expectLicenseType, "wrong licenseType");
                    Assert.assertEquals(description, expectDescription, "wrong description");
                    Assert.assertEquals(gspTypeName, expectgspTypeName, "wrong gspTypeName");
                    Assert.assertEquals(licenseTypeName, expcetLicenseTypeName, "wrong licenseTypeName");

                }

            }
        }
    } finally {
        //??  
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //  
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // http  
        if (httpClient != null) {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.vsct.strowgr.monitoring.aggregator.nsq.NsqLookupClient.java

public NsqLookupClient(String host, int port) {
    this.host = host;
    this.port = port;
    this.client = HttpClients.createDefault();
}

From source file:uk.codingbadgers.bootstrap.download.Sha1Download.java

@Override
public void download() {
    CloseableHttpClient client = HttpClients.createDefault();
    String hash = null;/*from  ww  w . j av a  2  s. c o  m*/

    // Get sha1 hash from repo
    try {
        HttpGet request = new HttpGet(remote + ".sha1");
        HttpResponse response = client.execute(request);

        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity entity = response.getEntity();
            hash = EntityUtils.toString(entity);
            EntityUtils.consume(entity);
        }
    } catch (IOException ex) {
        throw new BootstrapException(ex);
    }

    if (local.exists()) {
        String localHash = ChecksumGenerator.createSha1(local);

        if (hash != null && hash.equalsIgnoreCase(localHash)) {
            System.out.println("File " + local.getName() + " is up to date with remote, no need to download");
            return;
        }
    }

    if (!local.getParentFile().exists()) {
        local.getParentFile().mkdirs();
    }

    // Download library from remote
    try {
        HttpGet request = new HttpGet(remote);
        HttpResponse response = client.execute(request);

        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() == HttpStatus.SC_OK) {
            System.err.println("Downloading " + local.getName());

            HttpEntity entity = response.getEntity();

            ReadableByteChannel rbc = Channels.newChannel(entity.getContent());
            FileOutputStream fos = new FileOutputStream(local);
            fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);

            EntityUtils.consume(entity);

            String localHash = ChecksumGenerator.createSha1(local);
            if (hash != null && !localHash.equalsIgnoreCase(hash)) {
                throw new BootstrapException("Error downloading file (" + local.getName()
                        + ")\n[expected hash: " + localHash + " but got " + hash + "]");
            }

            System.out.println("Downloaded " + local.getName());

        } else {
            throw new BootstrapException("Error download update for " + local.getName() + ", Error: "
                    + status.getStatusCode() + status.getReasonPhrase());
        }
    } catch (IOException ex) {
        throw new BootstrapException(ex);
    }
}