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

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

Introduction

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

Prototype

public void close() throws IOException;

Source Link

Document

Closes this stream and releases any system resources associated with it.

Usage

From source file:eu.diacron.crawlservice.app.Util.java

public static JSONArray getwarcsByCrawlid(String crawlid) {

    JSONArray warcsArray = null;//from   w ww  .  ja  v a2 s . c o  m
    System.out.println("get crawlid");

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    /*        credsProvider.setCredentials(
     new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
     new UsernamePasswordCredentials("diachron", "7nD9dNGshTtficn"));
     */

    credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(Configuration.REMOTE_CRAWLER_USERNAME,
                    Configuration.REMOTE_CRAWLER_PASS));
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    try {

        //HttpGet httpget = new HttpGet("http://diachron.hanzoarchives.com/warcs/" + crawlid);
        HttpGet httpget = new HttpGet(Configuration.REMOTE_CRAWLER_URL + crawlid);

        System.out.println("Executing request " + httpget.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            System.out.println("----------------------------------------");

            String result = "";

            BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                System.out.println(inputLine);
                result += inputLine;
            }
            in.close();

            result = result.replace("u'", "'");
            result = result.replace("'", "\"");

            warcsArray = new JSONArray(result);

            for (int i = 0; i < warcsArray.length(); i++) {

                System.out.println("url to download: " + warcsArray.getString(i));

            }

            EntityUtils.consume(response.getEntity());
        } catch (JSONException ex) {
            Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            response.close();
        }
    } catch (IOException ex) {
        Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            httpclient.close();
        } catch (IOException ex) {
            Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    return warcsArray;
}

From source file:de.adesso.referencer.search.helper.ElasticConfig.java

public static String sendHttpRequest(String url, String requestBody, String requestType) throws IOException {
    String result = null;// www  .j a  v  a  2  s  .  c om
    CloseableHttpClient httpclient = HttpClients.createDefault();
    CloseableHttpResponse httpResponse;
    try {
        switch (requestType) {
        case "Get":
            httpResponse = httpclient.execute(new HttpGet(url));
            break;
        case "Post":
            HttpPost httppost = new HttpPost(url);
            if (requestBody != null)
                httppost.setEntity(new StringEntity(requestBody, DEFAULT_CHARSET));
            httpResponse = httpclient.execute(httppost);
            break;
        case "Put":
            HttpPut httpPut = new HttpPut(url);
            httpPut.addHeader("Content-Type", "application/json");
            httpPut.addHeader("Accept", "application/json");
            if (requestBody != null)
                httpPut.setEntity(new StringEntity(requestBody, DEFAULT_CHARSET));
            httpResponse = httpclient.execute(httpPut);
            break;
        case "Delete":
            httpResponse = httpclient.execute(new HttpDelete(url));
            break;
        default:
            httpResponse = httpclient.execute(new HttpGet(url));
            break;
        }
        try {
            HttpEntity entity1 = httpResponse.getEntity();
            if (entity1 != null) {
                long len = entity1.getContentLength();
                if (len != -1 && len < MAX_CONTENT_LENGTH) {
                    result = EntityUtils.toString(entity1, DEFAULT_CHARSET);
                } else {
                    System.out.println("Error!!!! entity length=" + len);
                }
            }
            EntityUtils.consume(entity1);
        } finally {
            httpResponse.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        httpclient.close();
    }
    return result;
}

From source file:net.ymate.platform.module.wechat.support.HttpClientHelper.java

public String doPost(String url, Map<String, String> params) throws Exception {
    CloseableHttpClient _httpClient = __doBuildHttpClient();
    try {/*from  w w w  . j  av  a 2  s  .  c  o  m*/
        _LOG.debug("Request URL [" + url + "] PostBody [" + params + "]");
        String _result = _httpClient.execute(
                RequestBuilder.post().setUri(url)
                        .setEntity(EntityBuilder.create().setContentEncoding(DEFAULT_CHARSET)
                                .setParameters(__doBuildNameValuePairs(params)).build())
                        .build(),
                new ResponseHandler<String>() {

                    public String handleResponse(HttpResponse response) throws IOException {
                        return EntityUtils.toString(response.getEntity(), DEFAULT_CHARSET);
                    }

                });
        _LOG.debug("Request URL [" + url + "] Response [" + _result + "]");
        return _result;
    } finally {
        _httpClient.close();
    }
}

From source file:com.yahoo.yrlhaifa.liveqa.challenge.http_operation.QuestionOperationHttpRequestSender.java

public void sendRequestsAndCollectAnswers() throws QuestionOperationException, InterruptedException {
    if (mapParticipantToAnswer.size() > 0) {
        throw new QuestionOperationException("BUG: The given map from system-id to answers is not empty.");
    }/* w w  w .  j  a  va2s .  c  o  m*/

    CloseableHttpClient httpClient = HttpClients.custom().setMaxConnPerRoute(participants.size()).build();
    try {
        ExecutorService executor = Executors.newFixedThreadPool(participants.size());
        try {
            FutureRequestExecutionService requestExecutor = new FutureRequestExecutionService(httpClient,
                    executor);
            logger.info("Sending requests using request-executor...");
            sendRequestsWithRequestExecutor(requestExecutor);
            logger.info("Sending requests using request-executor - done.");
        } finally {
            try {
                executor.shutdownNow();
            } catch (RuntimeException e) {
                // TODO Add more error handling
                logger.error("Failed to shutdown executor. Program continues.", e);
            }
        }

    } finally {
        try {
            httpClient.close();
        } catch (IOException | RuntimeException e) {
            // TODO Add more error handling
            logger.error("Failed to close HTTP client. Program continues.", e);
        }
    }

    // Remove those who did not finish on time, but did write results.
    Set<Participant> didNotSucceed = new LinkedHashSet<Participant>();
    for (Participant participant : mapParticipantToAnswer.keySet()) {
        if (!(systemsSucceeded.contains(participant))) {
            didNotSucceed.add(participant);
        }
    }
    for (Participant toRemove : didNotSucceed) {
        mapParticipantToAnswer.remove(toRemove);
    }

    if (exception != null) {
        throw exception;
    }
}

From source file:com.getblimp.api.client.Blimp.java

private String execute(HttpRequestBase request) throws IOException, RuntimeException {
    logger.fine("Entering Blimp.execute");

    CloseableHttpClient client = HttpClients.createDefault();

    logger.finer("Blimp.execute executing HTTP method: " + request.getMethod());
    HttpResponse response = client.execute(request);

    logger.finer("Response status code: " + String.valueOf(response.getStatusLine().getStatusCode()));
    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK
            && response.getStatusLine().getStatusCode() != HttpStatus.SC_ACCEPTED) {
        throw new RuntimeException("Request Failed: " + "HTTP Status code: "
                + String.valueOf(response.getStatusLine().getStatusCode()));
    }/*from ww  w  .j av a  2 s  .  co  m*/
    BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

    logger.finer("Reading response entity.");
    logger.finer("Output from Server ....");
    String tmpOutput;
    StringBuilder output = new StringBuilder();
    while ((tmpOutput = br.readLine()) != null) {
        output.append(tmpOutput);
    }

    client.close();

    logger.finer("Blimp.execute output: " + output.toString());
    return output.toString();
}

From source file:com.github.maoo.indexer.client.WebScriptsAlfrescoClient.java

@Override
public AlfrescoUser fetchUserAuthorities(String username) throws AlfrescoDownException {
    CloseableHttpResponse response = null;
    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {/*from w  ww  .  j ava 2  s .  c  o  m*/
        String url = String.format("%s%s", authoritiesUrl, username);

        if (logger.isDebugEnabled()) {
            logger.debug("Hitting url: " + url);
        }

        HttpGet httpGet = createGetRequest(url);
        response = httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        AlfrescoUser afResponse = userFromHttpEntity(entity);
        EntityUtils.consume(entity);
        return afResponse;
    } catch (IOException e) {
        if (logger.isDebugEnabled()) {
            logger.warn("Failed to fetch nodes.", e);
        }
        throw new AlfrescoDownException("Alfresco appears to be down", e);
    } finally {

        try {
            if (response != null)
                response.close();
            httpClient.close();
        } catch (IOException e) {
            // Nothing to do
        }
    }
}

From source file:aop.controller.RequestController.java

public void sendPostReq(int id, String type) throws Exception {

    boolean debug = false;
    String url = "http://localhost:1337/";

    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {//from   w  ww  .  j  a v  a  2  s. co m
        HttpPost post = new HttpPost(url);

        // add header
        post.setHeader("User-Agent", USER_AGENT);

        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        urlParameters.add(new BasicNameValuePair("id", Integer.toString(id)));
        urlParameters.add(new BasicNameValuePair("type", type));

        post.setEntity(new UrlEncodedFormEntity(urlParameters));

        HttpResponse response = httpClient.execute(post);
        if (debug) {
            System.out.println("\nSending 'POST' request to URL : " + url);
            System.out.println("Post parameters : " + post.getEntity());
            System.out.println("Response Code : " + response.getStatusLine().getStatusCode());

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

            StringBuffer result = new StringBuffer();
            String line = "";
            while ((line = rd.readLine()) != null) {
                result.append(line);
            }

            System.out.println(result.toString());
        }
    } finally {
        httpClient.close();
    }
}

From source file:hu.dolphio.tprttapi.service.TrackingFlushServiceTpImpl.java

private Assignable getAssignableFromTp(Integer assignableId) throws IOException {
    if (assignableMap.containsKey(assignableId)) {
        return assignableMap.get(assignableId);
    }/*from w w  w  .  j a v a 2  s. c o m*/
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(config)
            .setDefaultCredentialsProvider(credsProvider).build();

    LOG.info("Trying to get assignable: " + assignableId);
    String getUri = "/api/v1/Assignables/" + assignableId
            + "?include=[Id,TimeSpent,Effort,Project[Id,Name]]&format=json";
    HttpGet httpGet = new HttpGet(getUri);
    CloseableHttpResponse execute = httpclient.execute(targetHost, httpGet, clientContext);
    LOG.info("TP assignable download response: " + execute);
    if (HttpResponseStatus
            .getStatusByCode(execute.getStatusLine().getStatusCode()) != HttpResponseStatus.SUCCESS) {
        LOG.warn("[" + execute.getStatusLine().getStatusCode()
                + "] Downloading Assignable information from TargetProcess failed!");
        return null;
    }
    String projectsJson = IOUtils.toString(execute.getEntity().getContent(), "utf-8");
    httpclient.close();

    Assignable assignable = new ObjectMapper().readValue(projectsJson, Assignable.class);

    if (!assignableMap.containsKey(assignable.getAssignableId())) {
        assignableMap.put(assignable.getAssignableId(), assignable);
        return assignable;
    }
    return null;
}

From source file:com.code42.demo.RestInvoker.java

/**
 * Execuites CODE42 api/File to upload a single file into the root directory of the specified planUid
 * If the file is succesfully uploaded the response code of 204 is returned.
 * //from   w w w  .j  ava2  s  .  co  m
 * @param planUid 
 * @param sessionId
 * @param file
 * @return HTTP Response code as int
 * @throws Exception
 */

public int postFileAPI(String planUid, String sessionId, File file) throws Exception {

    int respCode;
    HttpClientBuilder hcs;
    CloseableHttpClient httpClient;
    hcs = HttpClients.custom().setDefaultCredentialsProvider(credsProvider);
    if (ssl) {
        hcs.setSSLSocketFactory(sslsf);
    }
    httpClient = hcs.build();
    StringBody planId = new StringBody(planUid, ContentType.TEXT_PLAIN);
    StringBody sId = new StringBody(sessionId, ContentType.TEXT_PLAIN);

    try {
        HttpPost httpPost = new HttpPost(ePoint + "/api/File");
        FileBody fb = new FileBody(file);
        HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("file", fb).addPart("planUid", planId)
                .addPart("sessionId", sId).build();
        httpPost.setEntity(reqEntity);
        CloseableHttpResponse resp = httpClient.execute(httpPost);
        try {
            m_log.info("executing " + httpPost.getRequestLine());
            m_log.info(resp.getStatusLine());
            respCode = resp.getStatusLine().getStatusCode();
        } finally {
            resp.close();
        }

    } finally {
        httpClient.close();
    }

    return respCode;
}

From source file:org.codice.alliance.nsili.endpoint.requests.FtpDestinationSink.java

@Override
public void writeFile(InputStream fileData, long size, String name, String contentType,
        List<Metacard> metacards) throws IOException {
    CloseableHttpClient httpClient = null;
    String urlPath = protocol + "://" + fileLocation.host_name + ":" + port + "/" + fileLocation.path_name + "/"
            + name;//from   w ww.  jav a  2  s  . co  m

    LOGGER.debug("Writing ordered file to URL: {}", urlPath);

    try {
        HttpPut putMethod = new HttpPut(urlPath);
        putMethod.addHeader(HTTP.CONTENT_TYPE, contentType);
        HttpEntity httpEntity = new InputStreamEntity(fileData, size);
        putMethod.setEntity(httpEntity);

        if (StringUtils.isNotEmpty(fileLocation.user_name) && fileLocation.password != null) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(fileLocation.host_name, port),
                    new UsernamePasswordCredentials(fileLocation.user_name, fileLocation.password));
            httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
        } else {
            httpClient = HttpClients.createDefault();
        }

        httpClient.execute(putMethod);
        fileData.close();
        putMethod.releaseConnection();
    } finally {
        if (httpClient != null) {
            httpClient.close();
        }
    }
}