Search in sources :

Example 6 with HttpUriRequest

use of org.apache.http.client.methods.HttpUriRequest in project elasticsearch by elastic.

the class RestClientSingleHostTests method testInternalHttpRequest.

/**
     * Verifies the content of the {@link HttpRequest} that's internally created and passed through to the http client
     */
@SuppressWarnings("unchecked")
public void testInternalHttpRequest() throws Exception {
    ArgumentCaptor<HttpAsyncRequestProducer> requestArgumentCaptor = ArgumentCaptor.forClass(HttpAsyncRequestProducer.class);
    int times = 0;
    for (String httpMethod : getHttpMethods()) {
        HttpUriRequest expectedRequest = performRandomRequest(httpMethod);
        verify(httpClient, times(++times)).<HttpResponse>execute(requestArgumentCaptor.capture(), any(HttpAsyncResponseConsumer.class), any(HttpClientContext.class), any(FutureCallback.class));
        HttpUriRequest actualRequest = (HttpUriRequest) requestArgumentCaptor.getValue().generateRequest();
        assertEquals(expectedRequest.getURI(), actualRequest.getURI());
        assertEquals(expectedRequest.getClass(), actualRequest.getClass());
        assertArrayEquals(expectedRequest.getAllHeaders(), actualRequest.getAllHeaders());
        if (expectedRequest instanceof HttpEntityEnclosingRequest) {
            HttpEntity expectedEntity = ((HttpEntityEnclosingRequest) expectedRequest).getEntity();
            if (expectedEntity != null) {
                HttpEntity actualEntity = ((HttpEntityEnclosingRequest) actualRequest).getEntity();
                assertEquals(EntityUtils.toString(expectedEntity), EntityUtils.toString(actualEntity));
            }
        }
    }
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) HttpEntity(org.apache.http.HttpEntity) HttpAsyncRequestProducer(org.apache.http.nio.protocol.HttpAsyncRequestProducer) HttpEntityEnclosingRequest(org.apache.http.HttpEntityEnclosingRequest) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpResponse(org.apache.http.HttpResponse) HttpAsyncResponseConsumer(org.apache.http.nio.protocol.HttpAsyncResponseConsumer) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) FutureCallback(org.apache.http.concurrent.FutureCallback)

Example 7 with HttpUriRequest

use of org.apache.http.client.methods.HttpUriRequest in project android_frameworks_base by ParanoidAndroid.

the class AndroidHttpClient method toCurl.

/**
     * Generates a cURL command equivalent to the given request.
     */
private static String toCurl(HttpUriRequest request, boolean logAuthToken) throws IOException {
    StringBuilder builder = new StringBuilder();
    builder.append("curl ");
    // add in the method
    builder.append("-X ");
    builder.append(request.getMethod());
    builder.append(" ");
    for (Header header : request.getAllHeaders()) {
        if (!logAuthToken && (header.getName().equals("Authorization") || header.getName().equals("Cookie"))) {
            continue;
        }
        builder.append("--header \"");
        builder.append(header.toString().trim());
        builder.append("\" ");
    }
    URI uri = request.getURI();
    // relative URI. We want an absolute URI.
    if (request instanceof RequestWrapper) {
        HttpRequest original = ((RequestWrapper) request).getOriginal();
        if (original instanceof HttpUriRequest) {
            uri = ((HttpUriRequest) original).getURI();
        }
    }
    builder.append("\"");
    builder.append(uri);
    builder.append("\"");
    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request;
        HttpEntity entity = entityRequest.getEntity();
        if (entity != null && entity.isRepeatable()) {
            if (entity.getContentLength() < 1024) {
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                entity.writeTo(stream);
                if (isBinaryContent(request)) {
                    String base64 = Base64.encodeToString(stream.toByteArray(), Base64.NO_WRAP);
                    builder.insert(0, "echo '" + base64 + "' | base64 -d > /tmp/$$.bin; ");
                    builder.append(" --data-binary @/tmp/$$.bin");
                } else {
                    String entityString = stream.toString();
                    builder.append(" --data-ascii \"").append(entityString).append("\"");
                }
            } else {
                builder.append(" [TOO MUCH DATA TO INCLUDE]");
            }
        }
    }
    return builder.toString();
}
Also used : HttpRequest(org.apache.http.HttpRequest) HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) Header(org.apache.http.Header) AbstractHttpEntity(org.apache.http.entity.AbstractHttpEntity) HttpEntity(org.apache.http.HttpEntity) HttpEntityEnclosingRequest(org.apache.http.HttpEntityEnclosingRequest) RequestWrapper(org.apache.http.impl.client.RequestWrapper) ByteArrayOutputStream(java.io.ByteArrayOutputStream) URI(java.net.URI)

Example 8 with HttpUriRequest

use of org.apache.http.client.methods.HttpUriRequest in project ribbon by Netflix.

the class NamedConnectionPoolTest method testConnectionPoolCounters.

@Test
public void testConnectionPoolCounters() throws Exception {
    // LogManager.getRootLogger().setLevel((Level)Level.DEBUG);
    NFHttpClient client = NFHttpClientFactory.getNamedNFHttpClient("google-NamedConnectionPoolTest");
    assertTrue(client.getConnectionManager() instanceof MonitoredConnectionManager);
    MonitoredConnectionManager connectionPoolManager = (MonitoredConnectionManager) client.getConnectionManager();
    connectionPoolManager.setDefaultMaxPerRoute(100);
    connectionPoolManager.setMaxTotal(200);
    assertTrue(connectionPoolManager.getConnectionPool() instanceof NamedConnectionPool);
    NamedConnectionPool connectionPool = (NamedConnectionPool) connectionPoolManager.getConnectionPool();
    System.out.println("Entries created: " + connectionPool.getCreatedEntryCount());
    System.out.println("Requests count: " + connectionPool.getRequestsCount());
    System.out.println("Free entries: " + connectionPool.getFreeEntryCount());
    System.out.println("Deleted :" + connectionPool.getDeleteCount());
    System.out.println("Released: " + connectionPool.getReleaseCount());
    for (int i = 0; i < 10; i++) {
        HttpUriRequest request = new HttpGet(server.getServerPath("/"));
        HttpResponse response = client.execute(request);
        EntityUtils.consume(response.getEntity());
        int statusCode = response.getStatusLine().getStatusCode();
        assertTrue(statusCode == 200 || statusCode == 302);
        Thread.sleep(500);
    }
    System.out.println("Entries created: " + connectionPool.getCreatedEntryCount());
    System.out.println("Requests count: " + connectionPool.getRequestsCount());
    System.out.println("Free entries: " + connectionPool.getFreeEntryCount());
    System.out.println("Deleted :" + connectionPool.getDeleteCount());
    System.out.println("Released: " + connectionPool.getReleaseCount());
    assertTrue(connectionPool.getCreatedEntryCount() >= 1);
    assertTrue(connectionPool.getRequestsCount() >= 10);
    assertTrue(connectionPool.getFreeEntryCount() >= 9);
    assertEquals(0, connectionPool.getDeleteCount());
    assertEquals(connectionPool.getReleaseCount(), connectionPool.getRequestsCount());
    assertEquals(connectionPool.getRequestsCount(), connectionPool.getCreatedEntryCount() + connectionPool.getFreeEntryCount());
    ConfigurationManager.getConfigInstance().setProperty("google-NamedConnectionPoolTest.ribbon." + CommonClientConfigKey.MaxTotalHttpConnections.key(), "50");
    ConfigurationManager.getConfigInstance().setProperty("google-NamedConnectionPoolTest.ribbon." + CommonClientConfigKey.MaxHttpConnectionsPerHost.key(), "10");
    assertEquals(50, connectionPoolManager.getMaxTotal());
    assertEquals(10, connectionPoolManager.getDefaultMaxPerRoute());
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) Test(org.junit.Test)

Example 9 with HttpUriRequest

use of org.apache.http.client.methods.HttpUriRequest in project ribbon by Netflix.

the class NFHttpMethodRetryHandler method retryRequest.

@Override
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "ICAST_INTEGER_MULTIPLY_CAST_TO_LONG")
public boolean retryRequest(final IOException exception, int executionCount, HttpContext context) {
    if (super.retryRequest(exception, executionCount, context)) {
        HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
        String methodName = request.getRequestLine().getMethod();
        String path = "UNKNOWN_PATH";
        if (request instanceof HttpUriRequest) {
            HttpUriRequest uriReq = (HttpUriRequest) request;
            path = uriReq.getURI().toString();
        }
        try {
            Thread.sleep(executionCount * this.sleepTimeFactorMs);
        } catch (InterruptedException e) {
            logger.warn("Interrupted while sleep before retrying http method " + methodName + " " + path, e);
        }
        DynamicCounter.increment(RETRY_COUNTER + methodName + ":" + path);
        return true;
    }
    return false;
}
Also used : HttpRequest(org.apache.http.HttpRequest) HttpUriRequest(org.apache.http.client.methods.HttpUriRequest)

Example 10 with HttpUriRequest

use of org.apache.http.client.methods.HttpUriRequest in project ribbon by Netflix.

the class HttpPrimeConnection method connect.

@Override
public boolean connect(Server server, String primeConnectionsURIPath) throws Exception {
    String url = "http://" + server.getHostPort() + primeConnectionsURIPath;
    logger.debug("Trying URL: {}", url);
    HttpUriRequest get = new HttpGet(url);
    HttpResponse response = null;
    try {
        response = client.execute(get);
        if (logger.isDebugEnabled() && response.getStatusLine() != null) {
            logger.debug("Response code:" + response.getStatusLine().getStatusCode());
        }
    } finally {
        get.abort();
    }
    return true;
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse)

Aggregations

HttpUriRequest (org.apache.http.client.methods.HttpUriRequest)183 Test (org.junit.Test)62 TestRequest (com.android.volley.mock.TestRequest)52 HttpGet (org.apache.http.client.methods.HttpGet)44 URI (java.net.URI)41 HttpResponse (org.apache.http.HttpResponse)41 HttpEntity (org.apache.http.HttpEntity)38 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)36 HttpPost (org.apache.http.client.methods.HttpPost)21 IOException (java.io.IOException)19 Header (org.apache.http.Header)18 JSONObject (org.json.JSONObject)18 BufferedReader (java.io.BufferedReader)17 InputStreamReader (java.io.InputStreamReader)17 PrintWriter (java.io.PrintWriter)17 StringWriter (java.io.StringWriter)17 HttpHost (org.apache.http.HttpHost)13 HttpPut (org.apache.http.client.methods.HttpPut)12 HttpEntityEnclosingRequest (org.apache.http.HttpEntityEnclosingRequest)11 HttpParams (org.apache.http.params.HttpParams)10