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

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

Introduction

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

Prototype

void setHeader(String str, String str2);

Source Link

Usage

From source file:com.flipkart.bifrost.http.HttpCallCommand.java

private T makeHttpCall() throws Exception {
    HttpUriRequest httpRequest = generateRequestObject();
    if (null != headers) {
        for (Map.Entry<String, String> header : headers.entrySet()) {
            httpRequest.setHeader(header.getKey(), header.getValue());
        }//  ww w  .  ja va 2s .c  om
    }
    CloseableHttpResponse response = null;
    try {
        response = client.execute(httpRequest);
        int statusCode = response.getStatusLine().getStatusCode();
        HttpEntity entity = response.getEntity();
        byte[] responseBytes = (null != entity) ? EntityUtils.toByteArray(entity) : null;
        if (statusCode != successStatus) {
            throw new BifrostException(BifrostException.ErrorCode.SUCCESS_STATUS_MISMATCH,
                    String.format("Call status mismatch. Expected %d Got %d", successStatus, statusCode));
        }
        return mapper.readValue(responseBytes, new TypeReference<T>() {
        });
    } finally {
        if (null != response) {
            try {
                response.close();
            } catch (IOException e) {
                logger.error("Error closing HTTP response: ", e);
            }
        }
    }
}

From source file:org.yamj.api.common.http.HttpClientWrapper.java

@SuppressWarnings("unused")
protected void prepareRequest(HttpUriRequest request) throws ClientProtocolException {
    if (randomUserAgent) {
        request.setHeader(HTTP.USER_AGENT, UserAgentSelector.randomUserAgent());
    }//  ww w .  j av a 2s  .c o m
}

From source file:net.sf.jsog.client.DefaultHttpClientImpl.java

/**
 * Executes a request and returns the resulting String.
 * @param request the request to execute.
 * @return the raw content string.//from w w w. j  a  va 2 s.c  o  m
 * @throws JsogClientException if the request fails.
 */
private synchronized String execute(final HttpUriRequest request) {
    request.setParams(params);

    // Set the request's headers
    for (Entry<String, String> header : headers.entrySet()) {
        request.setHeader(header.getKey(), header.getValue());
    }

    // Execute the request and get it's content
    HttpResponse response;
    String content;
    try {

        // Execute the request
        response = getClient().execute(request);

        // Get the response content
        content = EntityUtils.toString(response.getEntity(), charset);
    } catch (IOException e) {
        throw new JsogClientException("Get request failed.", e);
    }

    // Check the response code
    StatusLine sl = response.getStatusLine();
    if (sl.getStatusCode() != 200) {
        throw new Non200ResponseCodeException(sl.getStatusCode(), sl.getReasonPhrase(), content);
    }

    return content;
}

From source file:com.jgoetsch.eventtrader.source.HttpPollingMsgSource.java

public void receiveMsgs(HttpClient client) {
    NewMsgHandler msgHandler = new NewMsgHandler();
    HttpUriRequest req = createRequest();
    for (;;) {/*from   w w w  . java  2  s  .c o  m*/
        HttpEntity entity = null;
        try {
            if (isUseIfModifiedSince() && lastModifiedDate != null)
                req.setHeader("If-Modified-Since", lastModifiedDate);

            long startTime = System.currentTimeMillis();
            HttpResponse rsp = client.execute(req);
            if (rsp.containsHeader("Last-Modified")) {
                lastModifiedDate = rsp.getFirstHeader("Last-Modified").getValue();
                //log.debug("Resource last modified: " + lastModifiedDate);
            }
            entity = rsp.getEntity();
            if (rsp.getStatusLine().getStatusCode() >= 400) {
                log.warn("HTTP request to " + req.getURI().getHost() + " failed ["
                        + rsp.getStatusLine().getStatusCode() + " " + rsp.getStatusLine().getReasonPhrase()
                        + ", " + (System.currentTimeMillis() - startTime) + " ms]");

                // 400 level error should be unrecoverable so just quit out
                if (rsp.getStatusLine().getStatusCode() < 500)
                    return;
                else {
                    // give server some more time to recover before retrying if it returned 500 level error
                    // probably means site crashed and continuing to hit it will only make things worse
                    try {
                        Thread.sleep(pollingInterval * 6);
                    } catch (InterruptedException e) {
                    }
                }
            } else {
                boolean bContinue = true;
                if (entity != null && rsp.getStatusLine().getStatusCode() != 304) { // 304 = not modified
                    bContinue = getMsgParser().parseContent(entity.getContent(), entity.getContentLength(),
                            entity.getContentType() == null ? null : entity.getContentType().getValue(),
                            msgHandler);
                    msgHandler.nextPass();
                }
                if (log.isDebugEnabled()) {
                    log.debug(
                            "Checked site at " + req.getURI().getHost() + " ["
                                    + rsp.getStatusLine().getStatusCode() + " "
                                    + rsp.getStatusLine().getReasonPhrase() + ", "
                                    + (entity != null ? (entity.getContentLength() != -1
                                            ? entity.getContentLength() + " bytes, "
                                            : "unknown length, ") : "")
                                    + (System.currentTimeMillis() - startTime) + " ms]");
                }
                if (!bContinue)
                    return;
            }
        } catch (IOException e) {
            log.warn(e.getClass() + ": " + e.getMessage());
        } catch (Exception e) {
            log.warn(e.getClass() + ": " + e.getMessage(), e);
        } finally {
            if (entity != null) {
                // release connection gracefully
                try {
                    entity.consumeContent();
                } catch (IOException e) {
                }
            }
        }

        delay();
    }
}

From source file:org.pixmob.appengine.client.AppEngineClient.java

private HttpResponse executeWithAuth(HttpUriRequest request) throws IOException {
    request.setHeader("Cookie", "SACSID=" + authenticationCookie);
    return safelyExecute(delegate, request);
}

From source file:ch.cyberduck.core.googlestorage.GoogleStorageSession.java

@Override
protected boolean authorize(final HttpUriRequest request, final ProviderCredentials credentials)
        throws ServiceException {
    if (credentials instanceof OAuth2ProviderCredentials) {
        request.setHeader("x-goog-api-version", "2");
        final Credential tokens = ((OAuth2ProviderCredentials) credentials).getTokens();
        if (log.isDebugEnabled()) {
            log.debug(String.format("Authorizing service request with OAuth2 access token: %s",
                    tokens.getAccessToken()));
        }//from   ww w  .  ja  v a2  s .  c  o m
        request.setHeader("Authorization", String.format("OAuth %s", tokens.getAccessToken()));
        return true;
    }
    return false;
}

From source file:org.pixmob.appengine.client.AppEngineClient.java

private void configureRequest(HttpUriRequest req) {
    if (httpUserAgent != null) {
        req.setHeader(HTTP.USER_AGENT, httpUserAgent);
    }
}

From source file:org.ow2.proactive_grid_cloud_portal.cli.cmd.AbstractCommand.java

protected HttpResponseWrapper execute(HttpUriRequest request, ApplicationContext currentContext) {
    String sessionId = currentContext.getSessionId();
    if (sessionId != null) {
        request.setHeader("sessionid", sessionId);
    }//www  .  java2  s .  c om
    CommonHttpClientBuilder httpClientBuilder = new HttpClientBuilder().useSystemProperties();
    try {
        if ("https".equals(request.getURI().getScheme()) && currentContext.canInsecureAccess()) {
            httpClientBuilder.insecure(true);
        }
        HttpResponse response = httpClientBuilder.build().execute(request);
        return new HttpResponseWrapper(response);

    } catch (SSLPeerUnverifiedException sslException) {
        throw new CLIException(CLIException.REASON_OTHER,
                "SSL error. Perhaps HTTPS certificate could not be validated, "
                        + "you can try with -k or insecure() for insecure SSL connection.",
                sslException);
    } catch (Exception e) {
        throw new CLIException(CLIException.REASON_OTHER, e.getMessage(), e);
    } finally {
        ((HttpRequestBase) request).releaseConnection();
    }
}