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:org.gradle.cache.tasks.http.HttpTaskOutputCache.java

@Override
public boolean load(TaskCacheKey key, TaskOutputReader reader) throws IOException {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {//  www.j  a v a  2s. com
        final URI uri = root.resolve("./" + key.getHashCode());
        HttpGet httpGet = new HttpGet(uri);
        final CloseableHttpResponse response = httpClient.execute(httpGet);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Response for GET {}: {}", uri, response.getStatusLine());
        }
        try {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode >= 200 && statusCode < 300) {
                reader.readFrom(response.getEntity().getContent());
                return true;
            } else {
                return false;
            }
        } finally {
            response.close();
        }
    } finally {
        httpClient.close();
    }
}

From source file:impalapayapis.ApiRequestBank.java

public String doPost() {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    StringEntity entity;//  w w w  .j  av  a  2s.  com
    String out = "";

    try {
        entity = new StringEntity(params);
        HttpPost httppost = new HttpPost(url);
        httppost.setEntity(entity);
        HttpResponse response = httpclient.execute(httppost);

        // for debugging
        System.out.println(entity.getContentType());
        System.out.println(entity.getContentLength());
        System.out.println(EntityUtils.toString(entity));
        System.out.println(EntityUtils.toByteArray(entity).length);

        //System.out.println(           "----------------------------------------");

        System.out.println(response.getStatusLine());
        System.out.println(url);

        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        out = rd.readLine();
        JsonElement root = new JsonParser().parse(out);

        String specificvalue = root.getAsJsonObject().get("replace with key of the value to retrieve")
                .getAsString();
        System.out.println(specificvalue);

        /**
         * String line = ""; while ((line = rd.readLine()) != null) {
         * //System.out.println(line); }
        *
         */

    } catch (UnsupportedEncodingException e) {
        logger.error("UnsupportedEncodingException for URL: '" + url + "'");

        logger.error(ExceptionUtils.getStackTrace(e));
    } catch (ClientProtocolException e) {
        logger.error("ClientProtocolException for URL: '" + url + "'");
        logger.error(ExceptionUtils.getStackTrace(e));
    } catch (IOException e) {
        logger.error("IOException for URL: '" + url + "'");
        logger.error(ExceptionUtils.getStackTrace(e));
    }
    return out;
}

From source file:downloadwolkflow.getWorkFlowList.java

public static String[] getPageList() {
    String[] pageList = null;/*  w  w w .  j  a va2s  .  c om*/
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpGet httpget = new HttpGet("http://www.myexperiment.org/workflows");
        HttpResponse response = httpclient.execute(httpget);
        String mainpage = EntityUtils.toString(response.getEntity());
        Document mainDoc = Jsoup.parse(mainpage);
        Element pageinfo = mainDoc.select("div.pagination ").first();
        //            System.out.println(pageinfo.toString());
        Elements pagesElemenets = pageinfo.select("[href]");
        int pageSize = Integer.parseInt(pagesElemenets.get(pagesElemenets.size() - 2).text());
        pageList = new String[pageSize + 1];
        for (int i = 1; i <= pageSize; i++) {
            pageList[i] = "http://www.myexperiment.org/workflows?page=" + i;
        }

    } catch (IOException ex) {
        Logger.getLogger(getWorkFlowList.class.getName()).log(Level.SEVERE, null, ex);
    }
    return pageList;
}

From source file:mx.ipn.escom.supernaut.nile.logic.CommonBean.java

public CommonBean() {
    gson = new Gson();
    client = HttpClients.createDefault();
    modelType = (Class<Model>) ((ParameterizedType) getClass().getGenericSuperclass())
            .getActualTypeArguments()[0];
    baseUri = URI.create(HOST.toURI() + "/resources/" + modelType.getName().toLowerCase());
}

From source file:org.dspace.google.GoogleRecorderEventListener.java

public GoogleRecorderEventListener() {
    // httpclient is threadsafe so we only need one.
    httpclient = HttpClients.createDefault();
}

From source file:it.tai.solr.http.HttpInvoker.java

public SolrResponse getSolrReport(REPORT_ACTION action) throws IOException, UnsupportedActionException {

    String url;/*from ww w .j a  v  a2s  .  c  o m*/

    switch (action) {
    case SUMMARY:
        url = solrURL + "action=" + REPORT_ACTION.SUMMARY.getCode() + "&wt=json";
        break;
    case REPORT:
        url = solrURL + "action=" + REPORT_ACTION.REPORT.getCode() + "&wt=json";
        break;
    default:
        throw new UnsupportedActionException("Unsupported report action");
    }

    CloseableHttpClient httpclient = HttpClients.createDefault();

    try {
        HttpGet httpget = new HttpGet(url);
        logger.info("Excuting SOLR report request: " + httpget.getRequestLine());
        long currTime = System.currentTimeMillis();

        CloseableHttpResponse response = httpclient.execute(httpget);
        responseTime("SOLR report ", currTime);

        checkResponse(response);

        String data = EntityUtils.toString(response.getEntity());

        if (logger.isDebugEnabled()) {
            logger.debug("Response data \n" + data);
        }

        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS, true);

        JsonNode root = mapper.readTree(data).path("Summary").path("alfresco").path("Searcher");

        SolrResponse toReturn = mapper.readValue(root.traverse(), SolrResponse.class);
        toReturn.setRawResponse(data);
        toReturn.setUrl(httpget.getRequestLine().getUri());

        return toReturn;

    } finally {
        httpclient.close();
    }
}

From source file:org.knoxcraft.http.client.ClientMultipartFormPost.java

public static void upload(String url, String playerName, File jsonfile, File sourcefile)
        throws ClientProtocolException, IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*from  ww  w . j  a va2  s .  c om*/
        HttpPost httppost = new HttpPost(url);

        FileBody json = new FileBody(jsonfile);
        FileBody source = new FileBody(sourcefile);
        String jsontext = readFromFile(jsonfile);

        HttpEntity reqEntity = MultipartEntityBuilder.create()
                .addPart("playerName", new StringBody(playerName, ContentType.TEXT_PLAIN))
                .addPart("jsonfile", json).addPart("sourcefile", source)
                .addPart("language", new StringBody("java", ContentType.TEXT_PLAIN))
                .addPart("jsontext", new StringBody(jsontext, ContentType.TEXT_PLAIN)).addPart("sourcetext",
                        new StringBody("public class Foo {\n  int x=5\n}", ContentType.TEXT_PLAIN))
                .build();

        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());
                Scanner sc = new Scanner(resEntity.getContent());
                while (sc.hasNext()) {
                    System.out.println(sc.nextLine());
                }
                sc.close();
                EntityUtils.consume(resEntity);
            }
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:org.wso2.ml.client.MLClient.java

public CloseableHttpResponse createdDataSet(JSONObject datasetConf) throws IOException {
    CloseableHttpClient httpClient = HttpClients.createDefault();

    HttpPost httpPost = new HttpPost(mlHost + "/api/datasets/");
    httpPost.setHeader(MLConstants.AUTHORIZATION_HEADER, getBasicAuthKey());

    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
    multipartEntityBuilder.addPart("description",
            new StringBody(datasetConf.get("description").toString(), ContentType.TEXT_PLAIN));
    multipartEntityBuilder.addPart("sourceType",
            new StringBody(datasetConf.get("sourceType").toString(), ContentType.TEXT_PLAIN));
    multipartEntityBuilder.addPart("destination",
            new StringBody(datasetConf.get("destination").toString(), ContentType.TEXT_PLAIN));
    multipartEntityBuilder.addPart("dataFormat",
            new StringBody(datasetConf.get("dataFormat").toString(), ContentType.TEXT_PLAIN));
    multipartEntityBuilder.addPart("containsHeader",
            new StringBody(datasetConf.get("containsHeader").toString(), ContentType.TEXT_PLAIN));
    multipartEntityBuilder.addPart("datasetName",
            new StringBody(datasetConf.get("datasetName").toString(), ContentType.TEXT_PLAIN));
    multipartEntityBuilder.addPart("version",
            new StringBody(datasetConf.get("version").toString(), ContentType.TEXT_PLAIN));

    File file = new File(mlDatasetPath);
    multipartEntityBuilder.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM,
            datasetConf.get("file").toString());

    httpPost.setEntity(multipartEntityBuilder.build());
    return httpClient.execute(httpPost);

}

From source file:de._692b8c32.cdlauncher.tasks.GithubReleasesDownloadTask.java

@Override
public void doWork() {
    setProgress(-1);/*  w w  w  . ja v  a2s  .co m*/

    try {
        String realUrl = null;
        HttpClient client = HttpClients.createDefault();
        if (version.getValue() == null) {
            Pattern pattern = Pattern
                    .compile("<ul class=\"release-downloads\"> <li> <a href=\"([^\"]*)\" rel=\"nofollow\">");
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(
                    client.execute(new HttpGet(baseUrl + "latest")).getEntity().getContent()))) {
                Matcher matcher = pattern
                        .matcher(reader.lines().collect(Collectors.joining(" ")).replace("  ", ""));
                if (matcher.find()) {
                    realUrl = baseUrl.substring(0,
                            baseUrl.indexOf('/', baseUrl.indexOf('/', baseUrl.indexOf('/') + 1) + 1))
                            + matcher.group(1);
                }
            }
        } else {
            realUrl = baseUrl + "download/" + version.getValue() + "/OpenRA-" + version.getValue() + ".zip";
        }

        if (realUrl == null) {
            throw new RuntimeException("Failed to find real url");
        } else {
            try (InputStream stream = client.execute(new HttpGet(realUrl)).getEntity().getContent()) {
                Files.copy(stream, cacheFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
            }
        }
    } catch (IOException ex) {
        throw new RuntimeException("Could not download data", ex);
    }
}

From source file:com.navercorp.pinpoint.plugin.httpclient4.CloaeableHttpClientIT.java

@Test
public void test() throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*from   w w w.  j a va 2 s . c  o  m*/
        HttpGet httpget = new HttpGet("http://www.naver.com");
        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream instream = entity.getContent();
                try {
                    instream.read();
                } catch (IOException ex) {
                    throw ex;
                } finally {
                    instream.close();
                }
            }
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }

    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    verifier.printCache();

    verifier.verifyTrace(event("HTTP_CLIENT_4_INTERNAL",
            CloseableHttpClient.class.getMethod("execute", HttpUriRequest.class)));
    verifier.verifyTrace(event("HTTP_CLIENT_4_INTERNAL",
            PoolingHttpClientConnectionManager.class.getMethod("connect", HttpClientConnection.class,
                    HttpRoute.class, int.class, HttpContext.class),
            annotation("http.internal.display", "www.naver.com:80")));
    verifier.verifyTrace(event("HTTP_CLIENT_4",
            HttpRequestExecutor.class.getMethod("execute", HttpRequest.class, HttpClientConnection.class,
                    HttpContext.class),
            null, null, "www.naver.com", annotation("http.url", "/"), annotation("http.status.code", 200),
            annotation("http.io", anyAnnotationValue())));
    verifier.verifyTraceCount(0);
}