Search in sources :

Example 6 with Header

use of org.apache.http.Header in project elasticsearch by elastic.

the class RestClient method setHeaders.

private void setHeaders(HttpRequest httpRequest, Header[] requestHeaders) {
    Objects.requireNonNull(requestHeaders, "request headers must not be null");
    // request headers override default headers, so we don't add default headers if they exist as request headers
    final Set<String> requestNames = new HashSet<>(requestHeaders.length);
    for (Header requestHeader : requestHeaders) {
        Objects.requireNonNull(requestHeader, "request header must not be null");
        httpRequest.addHeader(requestHeader);
        requestNames.add(requestHeader.getName());
    }
    for (Header defaultHeader : defaultHeaders) {
        if (requestNames.contains(defaultHeader.getName()) == false) {
            httpRequest.addHeader(defaultHeader);
        }
    }
}
Also used : Header(org.apache.http.Header) HashSet(java.util.HashSet)

Example 7 with Header

use of org.apache.http.Header in project elasticsearch by elastic.

the class RestClientSingleHostTests method testHeaders.

/**
     * End to end test for request and response headers. Exercises the mock http client ability to send back
     * whatever headers it has received.
     */
public void testHeaders() throws IOException {
    for (String method : getHttpMethods()) {
        final Header[] requestHeaders = RestClientTestUtil.randomHeaders(getRandom(), "Header");
        final int statusCode = randomStatusCode(getRandom());
        Response esResponse;
        try {
            esResponse = restClient.performRequest(method, "/" + statusCode, requestHeaders);
        } catch (ResponseException e) {
            esResponse = e.getResponse();
        }
        assertThat(esResponse.getStatusLine().getStatusCode(), equalTo(statusCode));
        assertHeaders(defaultHeaders, requestHeaders, esResponse.getHeaders(), Collections.<String>emptySet());
    }
}
Also used : BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpResponse(org.apache.http.HttpResponse) Header(org.apache.http.Header)

Example 8 with Header

use of org.apache.http.Header in project elasticsearch by elastic.

the class RestClientBuilderTests method testBuild.

public void testBuild() throws IOException {
    try {
        RestClient.builder((HttpHost[]) null);
        fail("should have failed");
    } catch (NullPointerException e) {
        assertEquals("hosts must not be null", e.getMessage());
    }
    try {
        RestClient.builder();
        fail("should have failed");
    } catch (IllegalArgumentException e) {
        assertEquals("no hosts provided", e.getMessage());
    }
    try {
        RestClient.builder(new HttpHost("localhost", 9200), null);
        fail("should have failed");
    } catch (NullPointerException e) {
        assertEquals("host cannot be null", e.getMessage());
    }
    try (RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build()) {
        assertNotNull(restClient);
    }
    try {
        RestClient.builder(new HttpHost("localhost", 9200)).setMaxRetryTimeoutMillis(randomIntBetween(Integer.MIN_VALUE, 0));
        fail("should have failed");
    } catch (IllegalArgumentException e) {
        assertEquals("maxRetryTimeoutMillis must be greater than 0", e.getMessage());
    }
    try {
        RestClient.builder(new HttpHost("localhost", 9200)).setDefaultHeaders(null);
        fail("should have failed");
    } catch (NullPointerException e) {
        assertEquals("defaultHeaders must not be null", e.getMessage());
    }
    try {
        RestClient.builder(new HttpHost("localhost", 9200)).setDefaultHeaders(new Header[] { null });
        fail("should have failed");
    } catch (NullPointerException e) {
        assertEquals("default header must not be null", e.getMessage());
    }
    try {
        RestClient.builder(new HttpHost("localhost", 9200)).setFailureListener(null);
        fail("should have failed");
    } catch (NullPointerException e) {
        assertEquals("failureListener must not be null", e.getMessage());
    }
    try {
        RestClient.builder(new HttpHost("localhost", 9200)).setHttpClientConfigCallback(null);
        fail("should have failed");
    } catch (NullPointerException e) {
        assertEquals("httpClientConfigCallback must not be null", e.getMessage());
    }
    try {
        RestClient.builder(new HttpHost("localhost", 9200)).setRequestConfigCallback(null);
        fail("should have failed");
    } catch (NullPointerException e) {
        assertEquals("requestConfigCallback must not be null", e.getMessage());
    }
    int numNodes = randomIntBetween(1, 5);
    HttpHost[] hosts = new HttpHost[numNodes];
    for (int i = 0; i < numNodes; i++) {
        hosts[i] = new HttpHost("localhost", 9200 + i);
    }
    RestClientBuilder builder = RestClient.builder(hosts);
    if (randomBoolean()) {
        builder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {

            @Override
            public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                return httpClientBuilder;
            }
        });
    }
    if (randomBoolean()) {
        builder.setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() {

            @Override
            public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder requestConfigBuilder) {
                return requestConfigBuilder;
            }
        });
    }
    if (randomBoolean()) {
        int numHeaders = randomIntBetween(1, 5);
        Header[] headers = new Header[numHeaders];
        for (int i = 0; i < numHeaders; i++) {
            headers[i] = new BasicHeader("header" + i, "value");
        }
        builder.setDefaultHeaders(headers);
    }
    if (randomBoolean()) {
        builder.setMaxRetryTimeoutMillis(randomIntBetween(1, Integer.MAX_VALUE));
    }
    if (randomBoolean()) {
        String pathPrefix = (randomBoolean() ? "/" : "") + randomAsciiOfLengthBetween(2, 5);
        while (pathPrefix.length() < 20 && randomBoolean()) {
            pathPrefix += "/" + randomAsciiOfLengthBetween(3, 6);
        }
        builder.setPathPrefix(pathPrefix + (randomBoolean() ? "/" : ""));
    }
    try (RestClient restClient = builder.build()) {
        assertNotNull(restClient);
    }
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) HttpAsyncClientBuilder(org.apache.http.impl.nio.client.HttpAsyncClientBuilder) Matchers.containsString(org.hamcrest.Matchers.containsString) HttpAsyncClientBuilder(org.apache.http.impl.nio.client.HttpAsyncClientBuilder) BasicHeader(org.apache.http.message.BasicHeader) Header(org.apache.http.Header) HttpHost(org.apache.http.HttpHost) BasicHeader(org.apache.http.message.BasicHeader)

Example 9 with Header

use of org.apache.http.Header in project jersey by jersey.

the class ApacheConnector method apply.

@Override
public ClientResponse apply(final ClientRequest clientRequest) throws ProcessingException {
    final HttpUriRequest request = getUriHttpRequest(clientRequest);
    final Map<String, String> clientHeadersSnapshot = writeOutBoundHeaders(clientRequest.getHeaders(), request);
    try {
        final CloseableHttpResponse response;
        final HttpClientContext context = HttpClientContext.create();
        if (preemptiveBasicAuth) {
            final AuthCache authCache = new BasicAuthCache();
            final BasicScheme basicScheme = new BasicScheme();
            authCache.put(getHost(request), basicScheme);
            context.setAuthCache(authCache);
        }
        response = client.execute(getHost(request), request, context);
        HeaderUtils.checkHeaderChanges(clientHeadersSnapshot, clientRequest.getHeaders(), this.getClass().getName());
        final Response.StatusType status = response.getStatusLine().getReasonPhrase() == null ? Statuses.from(response.getStatusLine().getStatusCode()) : Statuses.from(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase());
        final ClientResponse responseContext = new ClientResponse(status, clientRequest);
        final List<URI> redirectLocations = context.getRedirectLocations();
        if (redirectLocations != null && !redirectLocations.isEmpty()) {
            responseContext.setResolvedRequestUri(redirectLocations.get(redirectLocations.size() - 1));
        }
        final Header[] respHeaders = response.getAllHeaders();
        final MultivaluedMap<String, String> headers = responseContext.getHeaders();
        for (final Header header : respHeaders) {
            final String headerName = header.getName();
            List<String> list = headers.get(headerName);
            if (list == null) {
                list = new ArrayList<>();
            }
            list.add(header.getValue());
            headers.put(headerName, list);
        }
        final HttpEntity entity = response.getEntity();
        if (entity != null) {
            if (headers.get(HttpHeaders.CONTENT_LENGTH) == null) {
                headers.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(entity.getContentLength()));
            }
            final Header contentEncoding = entity.getContentEncoding();
            if (headers.get(HttpHeaders.CONTENT_ENCODING) == null && contentEncoding != null) {
                headers.add(HttpHeaders.CONTENT_ENCODING, contentEncoding.getValue());
            }
        }
        try {
            responseContext.setEntityStream(new HttpClientResponseInputStream(getInputStream(response)));
        } catch (final IOException e) {
            LOGGER.log(Level.SEVERE, null, e);
        }
        return responseContext;
    } catch (final Exception e) {
        throw new ProcessingException(e);
    }
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) ClientResponse(org.glassfish.jersey.client.ClientResponse) BasicScheme(org.apache.http.impl.auth.BasicScheme) HttpEntity(org.apache.http.HttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) AbstractHttpEntity(org.apache.http.entity.AbstractHttpEntity) AuthCache(org.apache.http.client.AuthCache) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) IOException(java.io.IOException) URI(java.net.URI) ProcessingException(javax.ws.rs.ProcessingException) IOException(java.io.IOException) ClientResponse(org.glassfish.jersey.client.ClientResponse) Response(javax.ws.rs.core.Response) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) Header(org.apache.http.Header) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) ProcessingException(javax.ws.rs.ProcessingException)

Example 10 with Header

use of org.apache.http.Header in project hadoop by apache.

the class WebAppProxyServlet method proxyLink.

/**
   * Download link and have it be the response.
   * @param req the http request
   * @param resp the http response
   * @param link the link to download
   * @param c the cookie to set if any
   * @param proxyHost the proxy host
   * @param method the http method
   * @throws IOException on any error.
   */
private static void proxyLink(final HttpServletRequest req, final HttpServletResponse resp, final URI link, final Cookie c, final String proxyHost, final HTTP method) throws IOException {
    DefaultHttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY).setBooleanParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
    // Make sure we send the request from the proxy address in the config
    // since that is what the AM filter checks against. IP aliasing or
    // similar could cause issues otherwise.
    InetAddress localAddress = InetAddress.getByName(proxyHost);
    if (LOG.isDebugEnabled()) {
        LOG.debug("local InetAddress for proxy host: {}", localAddress);
    }
    client.getParams().setParameter(ConnRoutePNames.LOCAL_ADDRESS, localAddress);
    HttpRequestBase base = null;
    if (method.equals(HTTP.GET)) {
        base = new HttpGet(link);
    } else if (method.equals(HTTP.PUT)) {
        base = new HttpPut(link);
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream(), "UTF-8"));
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        ((HttpPut) base).setEntity(new StringEntity(sb.toString()));
    } else {
        resp.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        return;
    }
    @SuppressWarnings("unchecked") Enumeration<String> names = req.getHeaderNames();
    while (names.hasMoreElements()) {
        String name = names.nextElement();
        if (PASS_THROUGH_HEADERS.contains(name)) {
            String value = req.getHeader(name);
            if (LOG.isDebugEnabled()) {
                LOG.debug("REQ HEADER: {} : {}", name, value);
            }
            base.setHeader(name, value);
        }
    }
    String user = req.getRemoteUser();
    if (user != null && !user.isEmpty()) {
        base.setHeader("Cookie", PROXY_USER_COOKIE_NAME + "=" + URLEncoder.encode(user, "ASCII"));
    }
    OutputStream out = resp.getOutputStream();
    try {
        HttpResponse httpResp = client.execute(base);
        resp.setStatus(httpResp.getStatusLine().getStatusCode());
        for (Header header : httpResp.getAllHeaders()) {
            resp.setHeader(header.getName(), header.getValue());
        }
        if (c != null) {
            resp.addCookie(c);
        }
        InputStream in = httpResp.getEntity().getContent();
        if (in != null) {
            IOUtils.copyBytes(in, out, 4096, true);
        }
    } finally {
        base.releaseConnection();
    }
}
Also used : HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) InputStreamReader(java.io.InputStreamReader) ObjectInputStream(java.io.ObjectInputStream) InputStream(java.io.InputStream) HttpGet(org.apache.http.client.methods.HttpGet) OutputStream(java.io.OutputStream) HttpResponse(org.apache.http.HttpResponse) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpPut(org.apache.http.client.methods.HttpPut) StringEntity(org.apache.http.entity.StringEntity) Header(org.apache.http.Header) BufferedReader(java.io.BufferedReader) InetAddress(java.net.InetAddress)

Aggregations

Header (org.apache.http.Header)906 HttpResponse (org.apache.http.HttpResponse)368 HttpGet (org.apache.http.client.methods.HttpGet)253 Test (org.junit.Test)206 IOException (java.io.IOException)200 BasicHeader (org.apache.http.message.BasicHeader)160 HttpEntity (org.apache.http.HttpEntity)134 TestHttpClient (io.undertow.testutils.TestHttpClient)94 URI (java.net.URI)93 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)93 ArrayList (java.util.ArrayList)90 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)78 HashMap (java.util.HashMap)76 InputStream (java.io.InputStream)67 URISyntaxException (java.net.URISyntaxException)64 HttpPost (org.apache.http.client.methods.HttpPost)62 StatusLine (org.apache.http.StatusLine)60 List (java.util.List)52 StringEntity (org.apache.http.entity.StringEntity)51 HttpHost (org.apache.http.HttpHost)46