Search in sources :

Example 56 with CloseableHttpResponse

use of org.apache.http.client.methods.CloseableHttpResponse in project apn-proxy by apn-proxy.

the class TestProxyWithHttpClient method test.

private void test(String uri, int exceptCode, String exceptHeaderName, String exceptHeaderValue) {
    ConnectionConfig connectionConfig = ConnectionConfig.custom().setCharset(Consts.UTF_8).build();
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(2000);
    cm.setDefaultMaxPerRoute(40);
    cm.setDefaultConnectionConfig(connectionConfig);
    CloseableHttpClient httpClient = HttpClients.custom().setUserAgent("Mozilla/5.0 xx-dev-web-common httpclient/4.x").setConnectionManager(cm).disableContentCompression().disableCookieManagement().build();
    HttpHost proxy = new HttpHost("127.0.0.1", ApnProxyConfig.getConfig().getPort());
    RequestConfig config = RequestConfig.custom().setProxy(proxy).setExpectContinueEnabled(true).setConnectionRequestTimeout(5000).setConnectTimeout(10000).setSocketTimeout(10000).setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();
    HttpGet request = new HttpGet(uri);
    request.setConfig(config);
    try {
        CloseableHttpResponse httpResponse = httpClient.execute(request);
        Assert.assertEquals(exceptCode, httpResponse.getStatusLine().getStatusCode());
        if (StringUtils.isNotBlank(exceptHeaderName) && StringUtils.isNotBlank(exceptHeaderValue)) {
            Assert.assertEquals(exceptHeaderValue, httpResponse.getFirstHeader(exceptHeaderName).getValue());
        }
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        responseHandler.handleResponse(httpResponse);
        httpResponse.close();
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) RequestConfig(org.apache.http.client.config.RequestConfig) HttpHost(org.apache.http.HttpHost) HttpGet(org.apache.http.client.methods.HttpGet) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) BasicResponseHandler(org.apache.http.impl.client.BasicResponseHandler) IOException(java.io.IOException) ConnectionConfig(org.apache.http.config.ConnectionConfig) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager)

Example 57 with CloseableHttpResponse

use of org.apache.http.client.methods.CloseableHttpResponse in project YCSB by brianfrankcooper.

the class RestClient method httpExecute.

private int httpExecute(HttpEntityEnclosingRequestBase request, String data) throws IOException {
    requestTimedout.setIsSatisfied(false);
    Thread timer = new Thread(new Timer(execTimeout, requestTimedout));
    timer.start();
    int responseCode = 200;
    for (int i = 0; i < headers.length; i = i + 2) {
        request.setHeader(headers[i], headers[i + 1]);
    }
    InputStreamEntity reqEntity = new InputStreamEntity(new ByteArrayInputStream(data.getBytes()), ContentType.APPLICATION_FORM_URLENCODED);
    reqEntity.setChunked(true);
    request.setEntity(reqEntity);
    CloseableHttpResponse response = client.execute(request);
    responseCode = response.getStatusLine().getStatusCode();
    HttpEntity responseEntity = response.getEntity();
    // If null entity don't bother about connection release.
    if (responseEntity != null) {
        InputStream stream = responseEntity.getContent();
        if (compressedResponse) {
            stream = new GZIPInputStream(stream);
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
        StringBuffer responseContent = new StringBuffer();
        String line = "";
        while ((line = reader.readLine()) != null) {
            if (requestTimedout.isSatisfied()) {
                // Must avoid memory leak.
                reader.close();
                stream.close();
                EntityUtils.consumeQuietly(responseEntity);
                response.close();
                client.close();
                throw new TimeoutException();
            }
            responseContent.append(line);
        }
        timer.interrupt();
        // Closing the input stream will trigger connection release.
        stream.close();
    }
    EntityUtils.consumeQuietly(responseEntity);
    response.close();
    client.close();
    return responseCode;
}
Also used : HttpEntity(org.apache.http.HttpEntity) InputStreamReader(java.io.InputStreamReader) GZIPInputStream(java.util.zip.GZIPInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) InputStreamEntity(org.apache.http.entity.InputStreamEntity) GZIPInputStream(java.util.zip.GZIPInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) BufferedReader(java.io.BufferedReader)

Example 58 with CloseableHttpResponse

use of org.apache.http.client.methods.CloseableHttpResponse in project YCSB by brianfrankcooper.

the class RestClient method httpDelete.

private int httpDelete(String endpoint) throws IOException {
    requestTimedout.setIsSatisfied(false);
    Thread timer = new Thread(new Timer(execTimeout, requestTimedout));
    timer.start();
    int responseCode = 200;
    HttpDelete request = new HttpDelete(endpoint);
    for (int i = 0; i < headers.length; i = i + 2) {
        request.setHeader(headers[i], headers[i + 1]);
    }
    CloseableHttpResponse response = client.execute(request);
    responseCode = response.getStatusLine().getStatusCode();
    response.close();
    client.close();
    return responseCode;
}
Also used : HttpDelete(org.apache.http.client.methods.HttpDelete) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse)

Example 59 with CloseableHttpResponse

use of org.apache.http.client.methods.CloseableHttpResponse in project google-analytics-java by brsanthu.

the class GoogleAnalyticsThreadFactory method post.

@SuppressWarnings({ "rawtypes" })
public GoogleAnalyticsResponse post(GoogleAnalyticsRequest request) {
    GoogleAnalyticsResponse response = new GoogleAnalyticsResponse();
    if (!config.isEnabled()) {
        return response;
    }
    CloseableHttpResponse httpResponse = null;
    try {
        List<NameValuePair> postParms = new ArrayList<NameValuePair>();
        logger.debug("Processing " + request);
        //Process the parameters
        processParameters(request, postParms);
        //Process custom dimensions
        processCustomDimensionParameters(request, postParms);
        //Process custom metrics
        processCustomMetricParameters(request, postParms);
        logger.debug("Processed all parameters and sending the request " + postParms);
        HttpPost httpPost = new HttpPost(config.getUrl());
        httpPost.setEntity(new UrlEncodedFormEntity(postParms, UTF8));
        httpResponse = (CloseableHttpResponse) httpClient.execute(httpPost);
        response.setStatusCode(httpResponse.getStatusLine().getStatusCode());
        response.setPostedParms(postParms);
        EntityUtils.consumeQuietly(httpResponse.getEntity());
        if (config.isGatherStats()) {
            gatherStats(request);
        }
    } catch (Exception e) {
        if (e instanceof UnknownHostException) {
            logger.warn("Coudln't connect to Google Analytics. Internet may not be available. " + e.toString());
        } else {
            logger.warn("Exception while sending the Google Analytics tracker request " + request, e);
        }
    } finally {
        try {
            httpResponse.close();
        } catch (Exception e2) {
        //ignore
        }
    }
    return response;
}
Also used : BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) HttpPost(org.apache.http.client.methods.HttpPost) UnknownHostException(java.net.UnknownHostException) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) ArrayList(java.util.ArrayList) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException)

Example 60 with CloseableHttpResponse

use of org.apache.http.client.methods.CloseableHttpResponse in project gocd by gocd.

the class ServerBinaryDownloaderTest method shouldReturnFalseIfTheServerDoesNotRespondWithEntity.

@Test
public void shouldReturnFalseIfTheServerDoesNotRespondWithEntity() throws Exception {
    GoAgentServerHttpClientBuilder builder = mock(GoAgentServerHttpClientBuilder.class);
    CloseableHttpClient closeableHttpClient = mock(CloseableHttpClient.class);
    when(builder.build()).thenReturn(closeableHttpClient);
    CloseableHttpResponse httpResponse = mock(CloseableHttpResponse.class);
    when(closeableHttpClient.execute(any(HttpRequestBase.class))).thenReturn(httpResponse);
    ServerBinaryDownloader downloader = new ServerBinaryDownloader(builder, ServerUrlGeneratorMother.generatorFor("localhost", 9090));
    assertThat(downloader.download(DownloadableFile.AGENT), is(false));
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) GoAgentServerHttpClientBuilder(com.thoughtworks.go.agent.common.ssl.GoAgentServerHttpClientBuilder) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) Test(org.junit.Test)

Aggregations

CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)536 HttpGet (org.apache.http.client.methods.HttpGet)242 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)171 StringEntity (org.apache.http.entity.StringEntity)127 JsonNode (com.fasterxml.jackson.databind.JsonNode)125 Test (org.junit.Test)125 HttpPost (org.apache.http.client.methods.HttpPost)107 IOException (java.io.IOException)105 HttpEntity (org.apache.http.HttpEntity)103 Deployment (org.activiti.engine.test.Deployment)87 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)67 ProcessInstance (org.activiti.engine.runtime.ProcessInstance)57 InputStream (java.io.InputStream)53 HttpPut (org.apache.http.client.methods.HttpPut)50 Task (org.activiti.engine.task.Task)41 URI (java.net.URI)36 StatusLine (org.apache.http.StatusLine)34 HttpUriRequest (org.apache.http.client.methods.HttpUriRequest)34 HttpClientContext (org.apache.http.client.protocol.HttpClientContext)31 BufferedReader (java.io.BufferedReader)30