Example usage for org.apache.http.client.methods HttpUriRequest addHeader

List of usage examples for org.apache.http.client.methods HttpUriRequest addHeader

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpUriRequest addHeader.

Prototype

void addHeader(String str, String str2);

Source Link

Usage

From source file:com.ocp.picasa.GDataClient.java

private void callMethod(HttpUriRequest request, Operation operation) throws IOException {
    // Specify GData protocol version 2.0.
    request.addHeader("GData-Version", "2");

    // Indicate support for gzip-compressed responses.
    request.addHeader("Accept-Encoding", "gzip");

    // Specify authorization token if provided.
    String authToken = mAuthToken;
    if (!TextUtils.isEmpty(authToken)) {
        request.addHeader("Authorization", "GoogleLogin auth=" + authToken);
    }//  w  w w  .jav a 2 s  .  c o  m

    // Specify the ETag of a prior response, if available.
    String etag = operation.inOutEtag;
    if (etag != null) {
        request.addHeader("If-None-Match", etag);
    }

    // Execute the HTTP request.
    HttpResponse httpResponse = null;
    try {
        httpResponse = mHttpClient.execute(request);
    } catch (IOException e) {
        Log.w(Gallery.TAG, TAG + ": " + "Request failed: " + request.getURI());
        throw e;
    }

    // Get the status code and response body.
    int status = httpResponse.getStatusLine().getStatusCode();
    InputStream stream = null;
    HttpEntity entity = httpResponse.getEntity();
    if (entity != null) {
        // Wrap the entity input stream in a GZIP decoder if necessary.
        stream = entity.getContent();
        if (stream != null) {
            Header header = entity.getContentEncoding();
            if (header != null) {
                if (header.getValue().contains("gzip")) {
                    stream = new GZIPInputStream(stream);
                }
            }
        }
    }

    // Return the stream if successful.
    Header etagHeader = httpResponse.getFirstHeader("ETag");
    operation.outStatus = status;
    operation.inOutEtag = etagHeader != null ? etagHeader.getValue() : null;
    operation.outBody = stream;
}

From source file:org.codehaus.httpcache4j.resolver.HTTPClientResponseResolver.java

private HttpUriRequest convertRequest(HTTPRequest request) {
    HttpUriRequest realRequest = getMethod(request.getMethod(), request.getRequestURI());

    Headers headers = request.getAllHeaders();
    for (Header header : headers) {
        realRequest.addHeader(header.getName(), header.getValue());
    }/*from w  w  w . j  a  v  a  2  s  .c o  m*/

    if (request.hasPayload() && realRequest instanceof HttpEntityEnclosingRequest) {
        HttpEntityEnclosingRequest req = (HttpEntityEnclosingRequest) realRequest;
        req.setEntity(new UnknownLengthInputStreamEntity(request.getPayload()));
    }
    return realRequest;
}

From source file:org.fcrepo.integration.AbstractResourceIT.java

protected Dataset getDataset(final HttpClient client, final HttpUriRequest method) throws IOException {

    if (method.getFirstHeader(ACCEPT) == null) {
        method.addHeader(ACCEPT, "application/n-triples");
    } else {/* w  w  w .ja v  a 2  s  .com*/
        logger.debug("Retrieving RDF in mimeType: {}", method.getFirstHeader(ACCEPT));
    }

    final HttpResponse response = client.execute(method);
    assertEquals(OK.getStatusCode(), response.getStatusLine().getStatusCode());
    final Dataset result = parseTriples(response.getEntity());
    logger.trace("Retrieved RDF: {}", result);
    return result;

}

From source file:org.hawkular.apm.tests.agent.opentracing.client.http.ApacheHttpClientITest.java

protected void testHttpClientWithResponseHandler(HttpUriRequest request, boolean fault) throws IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*from ww  w  . ja  va 2  s  .  c o m*/
        request.addHeader("test-header", "test-value");
        if (fault) {
            request.addHeader("test-fault", "true");
        }

        // Create a custom response handler
        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

            @Override
            public String handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();

                assertEquals("Unexpected response code", 200, status);

                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            }

        };

        String responseBody = httpclient.execute(request, responseHandler);

        assertEquals(HELLO_WORLD, responseBody);

    } catch (ConnectException ce) {
        assertEquals(BAD_URL, request.getURI().toString());
    } finally {
        httpclient.close();
    }

    Wait.until(() -> getTracer().finishedSpans().size() == 1);

    List<MockSpan> spans = getTracer().finishedSpans();
    assertEquals(1, spans.size());
    assertEquals(Tags.SPAN_KIND_CLIENT, spans.get(0).tags().get(Tags.SPAN_KIND.getKey()));
    assertEquals(request.getMethod(), spans.get(0).operationName());
    assertEquals(request.getURI().toString(), spans.get(0).tags().get(Tags.HTTP_URL.getKey()));
    if (fault) {
        assertEquals("401", spans.get(0).tags().get(Tags.HTTP_STATUS.getKey()));
    }
}

From source file:com.timtory.wmgallery.picasa.GDataClient.java

private void callMethod(HttpUriRequest request, Operation operation) throws IOException {
    try {/*from   w ww  . ja v  a  2 s  . co m*/

        // Specify GData protocol version 2.0.
        request.addHeader("GData-Version", "2");

        // Indicate support for gzip-compressed responses.
        request.addHeader("Accept-Encoding", "gzip");

        // Specify authorization token if provided.
        String authToken = mAuthToken;
        if (!TextUtils.isEmpty(authToken)) {
            request.addHeader("Authorization", "GoogleLogin auth=" + authToken);
        }

        // Specify the ETag of a prior response, if available.
        String etag = operation.inOutEtag;
        if (etag != null) {
            request.addHeader("If-None-Match", etag);
        }

        // Execute the HTTP request.
        HttpResponse httpResponse = null;
        try {
            httpResponse = mHttpClient.execute(request);
        } catch (IOException e) {
            Log.w(TAG, "Request failed: " + request.getURI());
            throw e;
        }

        // Get the status code and response body.
        int status = httpResponse.getStatusLine().getStatusCode();
        InputStream stream = null;
        HttpEntity entity = httpResponse.getEntity();
        if (entity != null) {
            // Wrap the entity input stream in a GZIP decoder if necessary.
            stream = entity.getContent();
            if (stream != null) {
                Header header = entity.getContentEncoding();
                if (header != null) {
                    if (header.getValue().contains("gzip")) {
                        stream = new GZIPInputStream(stream);
                    }
                }
            }
        }

        // Return the stream if successful.
        Header etagHeader = httpResponse.getFirstHeader("ETag");
        operation.outStatus = status;
        operation.inOutEtag = etagHeader != null ? etagHeader.getValue() : null;
        operation.outBody = stream;

    } catch (java.lang.IllegalStateException e) {
        Log.e(TAG, "Unhandled IllegalStateException e: " + e);
        throw new IOException("Unhandled IllegalStateException");
    }
}

From source file:com.github.tomakehurst.wiremock.testsupport.WireMockTestClient.java

private WireMockResponse executeMethodAndConvertExceptions(HttpUriRequest httpRequest,
        TestHttpHeader... headers) {/*from   w  w w .j a  v a  2s . c o  m*/
    try {
        for (TestHttpHeader header : headers) {
            httpRequest.addHeader(header.getName(), header.getValue());
        }
        HttpResponse httpResponse = httpClient().execute(httpRequest);
        return new WireMockResponse(httpResponse);
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
}

From source file:com.palominolabs.crm.sf.rest.HttpApiClient.java

@Nonnull
private ProcessedResponse executeRequest(HttpUriRequest request) throws IOException {
    request.addHeader("Authorization", "OAuth " + this.oauthToken);
    HttpResponse response = this.client.execute(request);

    return new ProcessedResponse(response, checkResponse(request, response));
}

From source file:de.adorsys.forge.plugin.curl.CurlPlugin.java

private void setHeaders(HttpUriRequest request, String headers) {
    Map<String, String> parseHeader = HeaderCommandCompleter.parseHeader(headers);
    Set<Entry<String, String>> entrySet = parseHeader.entrySet();
    for (Entry<String, String> header : entrySet) {
        request.addHeader(header.getKey(), header.getValue());
    }/*from w  ww . j av  a  2  s  .com*/
}

From source file:com.klinker.android.spotify.loader.OAuthTokenRefresher.java

/**
 * Add an auth header to request// ww w. j a  va 2 s.  c  o  m
 */
protected HttpUriRequest addAuthHeader(HttpUriRequest request) {
    byte[] base64 = Base64.encode((getClientId() + ":" + getClientSecret()).getBytes(), Base64.DEFAULT);
    String authorization = new String(base64).replace("\n", "").replace(" ", "");
    request.addHeader("Authorization", "Basic " + authorization);
    request.addHeader("Content-Type", "application/x-www-form-urlencoded"); // need this or we get xml returned
    return request;
}

From source file:com.nxt.zyl.data.volley.toolbox.HttpClientStack.java

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    HttpUriRequest httpRequest = createHttpRequest(request, additionalHeaders);
    // add gzip support, not all request need gzip support
    if (request.isShouldGzip()) {
        httpRequest.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
    }/*from w ww .j ava 2s .c o  m*/
    addHeaders(httpRequest, additionalHeaders);
    addHeaders(httpRequest, request.getHeaders());
    onPrepareRequest(httpRequest);
    HttpParams httpParams = httpRequest.getParams();
    int timeoutMs = request.getTimeoutMs();
    // TODO: Reevaluate this connection timeout based on more wide-scale
    // data collection and possibly different for wifi vs. 3G.
    HttpConnectionParams.setConnectionTimeout(httpParams, CONNECTION_TIME_OUT_MS);
    HttpConnectionParams.setSoTimeout(httpParams, timeoutMs);
    HttpResponse response = mClient.execute(httpRequest);
    if (response != null) {
        final HttpEntity entity = response.getEntity();
        if (entity == null) {
            return response;
        }
        final Header encoding = entity.getContentEncoding();
        if (encoding != null) {
            for (HeaderElement element : encoding.getElements()) {
                if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                    response.setEntity(new InflatingEntity(response.getEntity()));
                    break;
                }
            }
        }
    }
    return response;
}