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

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

Introduction

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

Prototype

public void addHeader(String str, String str2) 

Source Link

Usage

From source file:com.flipkart.poseidon.handlers.http.impl.HttpConnectionPool.java

/** Method to execute a request */
public HttpResponse execute(HttpRequestBase request) throws Exception {
    if (processQueue.tryAcquire()) {
        HttpResponse response;/*from ww  w . ja va 2s .com*/
        try {
            // Inject timestamp in milliseconds just before sending request on wire.
            // This will help in measuring latencies between client and server.
            if (request.getHeaders(TIMESTAMP_HEADER).length == 0) {
                request.addHeader(TIMESTAMP_HEADER, String.valueOf(System.currentTimeMillis()));
            }
            response = client.execute(request);
        } catch (Exception e) {
            logger.error("Connections: {} AvailableRequests: {}",
                    ((PoolingClientConnectionManager) this.client.getConnectionManager()).getTotalStats(),
                    processQueue.availablePermits());
            throw e;
        } finally {
            processQueue.release();
        }
        return response;
    } else {
        throw new Exception("PROCESS_QUEUE_FULL POOL:" + name);
    }
}

From source file:com.getblimp.api.client.Blimp.java

private HttpRequestBase createRequestMethod(String url, HttpMethods method) throws Exception {
    logger.fine("Entering Blimp.createRequestMethod");
    logger.finer("HTTP method: " + method.toString());

    HttpRequestBase tmpRequest;

    switch (method) {
    case GET://from   w w w. j  a  va2  s .  c  o  m
        tmpRequest = new HttpGet(url);
        break;
    case POST:
        tmpRequest = new HttpPost(url);
        break;
    case PUT:
        tmpRequest = new HttpPut(url);
        break;
    case PATCH:
        tmpRequest = new HttpPatch(url);
        break;
    default:
        throw new Exception("Wrong HTTP method.");
    }
    logger.finer("Adding request headers");
    tmpRequest.addHeader(resourceBundle.getString(BlimpHttpHeaders.AUTHORIZATION.getValue()),
            "ApiKey " + this.userName + ":" + this.apiKey);
    tmpRequest.addHeader(resourceBundle.getString(BlimpHttpHeaders.APPID.getValue()), this.applicationId);
    tmpRequest.addHeader(resourceBundle.getString(BlimpHttpHeaders.APPSECRET.getValue()),
            this.applicationSecret);

    logger.finer("Created request method: " + tmpRequest.getMethod());
    return tmpRequest;
}

From source file:com.mirth.connect.client.core.ServerConnection.java

private HttpRequestBase setupRequestBase(ClientRequest request, ExecuteType executeType) {
    HttpRequestBase requestBase = getRequestBase(executeType, request.getMethod());
    requestBase.setURI(request.getUri());

    for (Entry<String, List<String>> entry : request.getStringHeaders().entrySet()) {
        for (String value : entry.getValue()) {
            requestBase.addHeader(entry.getKey(), value);
        }//from  w  w  w .jav  a  2s  .  co m
    }

    if (request.hasEntity() && requestBase instanceof HttpEntityEnclosingRequestBase) {
        final HttpEntityEnclosingRequestBase entityRequestBase = (HttpEntityEnclosingRequestBase) requestBase;
        entityRequestBase.setEntity(new ClientRequestEntity(request));
    }

    return requestBase;
}

From source file:org.dasein.cloud.aws.platform.CloudFrontMethod.java

CloudFrontResponse invoke(String... args) throws CloudFrontException, CloudException, InternalException {
    ProviderContext ctx = provider.getContext();

    if (ctx == null) {
        throw new InternalException("Context not specified for this request");
    }/* w  w w  .java2s  .  c om*/
    StringBuilder url = new StringBuilder();
    String dateString = getDate();
    HttpRequestBase method;
    HttpClient client;

    url.append(CLOUD_FRONT_URL + "/" + CF_VERSION + "/distribution");
    if (args != null && args.length > 0) {
        for (String arg : args) {
            url.append("/");
            url.append(arg);
        }
    }
    method = action.getMethod(url.toString());
    method.addHeader(AWSCloud.P_AWS_DATE, dateString);
    try {
        String signature = provider.signCloudFront(new String(ctx.getAccessPublic(), "utf-8"),
                ctx.getAccessPrivate(), dateString);

        method.addHeader(AWSCloud.P_CFAUTH, signature);
    } catch (UnsupportedEncodingException e) {
        logger.error(e);
        e.printStackTrace();
        throw new InternalException(e);
    }
    if (headers != null) {
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            method.addHeader(entry.getKey(), entry.getValue());
        }
    }
    if (body != null) {
        try {
            ((HttpEntityEnclosingRequestBase) method)
                    .setEntity(new StringEntity(body, "application/xml", "utf-8"));
        } catch (UnsupportedEncodingException e) {
            throw new InternalException(e);
        }
    }
    attempts++;
    client = getClient(url.toString());
    CloudFrontResponse response = new CloudFrontResponse();

    HttpResponse httpResponse;
    int status;

    try {
        APITrace.trace(provider, action.toString());
        httpResponse = client.execute(method);
        status = httpResponse.getStatusLine().getStatusCode();

    } catch (IOException e) {
        logger.error(e);
        e.printStackTrace();
        throw new InternalException(e);
    }
    Header header = httpResponse.getFirstHeader("ETag");

    if (header != null) {
        response.etag = header.getValue();
    } else {
        response.etag = null;
    }
    if (status == HttpServletResponse.SC_OK || status == HttpServletResponse.SC_CREATED
            || status == HttpServletResponse.SC_ACCEPTED) {
        try {
            HttpEntity entity = httpResponse.getEntity();

            if (entity == null) {
                throw new CloudFrontException(status, null, null, "NoResponse",
                        "No response body was specified");
            }
            InputStream input;

            try {
                input = entity.getContent();
            } catch (IOException e) {
                throw new CloudException(e);
            }
            try {
                response.document = parseResponse(input);
                return response;
            } finally {
                input.close();
            }
        } catch (IOException e) {
            logger.error(e);
            e.printStackTrace();
            throw new CloudException(e);
        }
    } else if (status == HttpServletResponse.SC_NO_CONTENT) {
        return null;
    } else {
        if (status == HttpServletResponse.SC_SERVICE_UNAVAILABLE
                || status == HttpServletResponse.SC_INTERNAL_SERVER_ERROR) {
            if (attempts >= 5) {
                String msg;

                if (status == HttpServletResponse.SC_SERVICE_UNAVAILABLE) {
                    msg = "Cloud service is currently unavailable.";
                } else {
                    msg = "The cloud service encountered a server error while processing your request.";
                }
                logger.error(msg);
                throw new CloudException(msg);
            } else {
                try {
                    Thread.sleep(5000L);
                } catch (InterruptedException ignore) {
                }
                return invoke(args);
            }
        }
        try {
            HttpEntity entity = httpResponse.getEntity();

            if (entity == null) {
                throw new CloudFrontException(status, null, null, "NoResponse",
                        "No response body was specified");
            }
            InputStream input;

            try {
                input = entity.getContent();
            } catch (IOException e) {
                throw new CloudException(e);
            }
            Document doc;

            try {
                doc = parseResponse(input);
            } finally {
                input.close();
            }
            if (doc != null) {
                String code = null, message = null, requestId = null, type = null;
                NodeList blocks = doc.getElementsByTagName("Error");

                if (blocks.getLength() > 0) {
                    Node error = blocks.item(0);
                    NodeList attrs;

                    attrs = error.getChildNodes();
                    for (int i = 0; i < attrs.getLength(); i++) {
                        Node attr = attrs.item(i);

                        if (attr.getNodeName().equals("Code")) {
                            code = attr.getFirstChild().getNodeValue().trim();
                        } else if (attr.getNodeName().equals("Type")) {
                            type = attr.getFirstChild().getNodeValue().trim();
                        } else if (attr.getNodeName().equals("Message")) {
                            message = attr.getFirstChild().getNodeValue().trim();
                        }
                    }

                }
                blocks = doc.getElementsByTagName("RequestId");
                if (blocks.getLength() > 0) {
                    Node id = blocks.item(0);

                    requestId = id.getFirstChild().getNodeValue().trim();
                }
                if (message == null) {
                    throw new CloudException(
                            "Unable to identify error condition: " + status + "/" + requestId + "/" + code);
                }
                throw new CloudFrontException(status, requestId, type, code, message);
            }
            throw new CloudException("Unable to parse error.");
        } catch (IOException e) {
            logger.error(e);
            e.printStackTrace();
            throw new CloudException(e);
        }
    }
}

From source file:org.dcache.srm.client.HttpClientSender.java

/**
 * Creates a HttpRequest encoding a particular SOAP call.
 *
 * Called once per SOAP call.//from w  ww .  jav a 2  s .c o m
 */
protected HttpUriRequest createHttpRequest(MessageContext msgContext, URI url) throws AxisFault {
    boolean posting = true;
    // If we're SOAP 1.2, allow the web method to be set from the
    // MessageContext.
    if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
        String webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD);
        if (webMethod != null) {
            posting = webMethod.equals(HTTPConstants.HEADER_POST);
        }
    }

    HttpRequestBase request = posting ? new HttpPost(url) : new HttpGet(url);

    // Get SOAPAction, default to ""
    String action = msgContext.useSOAPAction() ? msgContext.getSOAPActionURI() : "";
    if (action == null) {
        action = "";
    }

    Message msg = msgContext.getRequestMessage();
    request.addHeader(HTTPConstants.HEADER_CONTENT_TYPE, msg.getContentType(msgContext.getSOAPConstants()));
    request.addHeader(HTTPConstants.HEADER_SOAP_ACTION, "\"" + action + "\"");

    String httpVersion = msgContext.getStrProp(MessageContext.HTTP_TRANSPORT_VERSION);
    if (httpVersion != null && httpVersion.equals(HTTPConstants.HEADER_PROTOCOL_V10)) {
        request.setProtocolVersion(HttpVersion.HTTP_1_0);
    }

    // Transfer MIME headers of SOAPMessage to HTTP headers.
    MimeHeaders mimeHeaders = msg.getMimeHeaders();
    if (mimeHeaders != null) {
        Iterator i = mimeHeaders.getAllHeaders();
        while (i.hasNext()) {
            MimeHeader mimeHeader = (MimeHeader) i.next();
            // HEADER_CONTENT_TYPE and HEADER_SOAP_ACTION are already set.
            // Let's not duplicate them.
            String name = mimeHeader.getName();
            if (!name.equals(HTTPConstants.HEADER_CONTENT_TYPE)
                    && !name.equals(HTTPConstants.HEADER_SOAP_ACTION)) {
                request.addHeader(name, mimeHeader.getValue());
            }
        }
    }

    boolean isChunked = false;
    boolean isExpectContinueEnabled = false;
    Map<?, ?> userHeaderTable = (Map) msgContext.getProperty(HTTPConstants.REQUEST_HEADERS);
    if (userHeaderTable != null) {
        for (Map.Entry<?, ?> me : userHeaderTable.entrySet()) {
            Object keyObj = me.getKey();
            if (keyObj != null) {
                String key = keyObj.toString().trim();
                String value = me.getValue().toString().trim();
                if (key.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT)) {
                    isExpectContinueEnabled = value.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT_100_Continue);
                } else if (key.equalsIgnoreCase(HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED)) {
                    isChunked = JavaUtils.isTrue(value);
                } else {
                    request.addHeader(key, value);
                }
            }
        }
    }

    RequestConfig.Builder config = RequestConfig.custom();
    // optionally set a timeout for the request
    if (msgContext.getTimeout() != 0) {
        /* ISSUE: these are not the same, but MessageContext has only one definition of timeout */
        config.setSocketTimeout(msgContext.getTimeout()).setConnectTimeout(msgContext.getTimeout());
    } else if (clientProperties.getConnectionPoolTimeout() != 0) {
        config.setConnectTimeout(clientProperties.getConnectionPoolTimeout());
    }
    config.setContentCompressionEnabled(msgContext.isPropertyTrue(HTTPConstants.MC_ACCEPT_GZIP));
    config.setExpectContinueEnabled(isExpectContinueEnabled);
    request.setConfig(config.build());

    if (request instanceof HttpPost) {
        HttpEntity requestEntity = new MessageEntity(request, msgContext.getRequestMessage(), isChunked);
        if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
            requestEntity = new GzipCompressingEntity(requestEntity);
        }
        ((HttpPost) request).setEntity(requestEntity);
    }

    return request;
}

From source file:co.uk.alt236.restclient4android.net.Connection.java

private void setAuthentication(HttpRequestBase con, NetworkRequest req) {
    Log.i(TAG, "^ CONNECTION: Adding authentication");

    String reqString = req.getAuthenticationMethod();

    if (reqString != null && reqString.length() > 0) {
        reqString = reqString.toLowerCase();
        if ("none".equals(reqString)) {
            return;
        } else if ("basic".equals(reqString)) {
            byte[] token = (req.getUsername() + ":" + req.getPassword()).getBytes();
            String authorizationString = "Basic " + Base64.encodeBytes(token);
            con.addHeader("Authorization", authorizationString);
        } else {//w ww  . j  a va2 s.c o m
            Log.w(TAG, "^ Unknown authentication method: '" + reqString + "'");
        }

    }
}

From source file:se.kodapan.io.http.HttpAccessor.java

public Response sendRequest(HttpRequestBase method, boolean followRedirects) throws IOException {

    // lazy opening
    if (!open) {/*from ww w .  j av a 2s .  c  o  m*/
        open();
    }

    // Mimics a Firefox on OS X.

    if (method.getHeaders("User-Agent").length == 0) {
        method.addHeader("User-Agent",
                "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; sv-SE; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2");
    }
    if (method.getHeaders("Accept").length == 0) {
        method.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    }
    if (method.getHeaders("Accept-Language").length == 0) {
        method.addHeader("Accept-Language", "sv-se,sv;q=0.8,en-us;q=0.5,en;q=0.3");
    }
    if (method.getHeaders("Accept-Charset").length == 0) {
        method.addHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
    }

    Response response = new Response();
    URI url = method.getURI();
    response.finalURL = url;

    if (log.isDebugEnabled()) {
        log.debug("Requesting " + url);
    }

    String tmp = url.toString().toLowerCase();
    if (!(tmp.startsWith("http://") || tmp.startsWith("https://"))) {
        log.error("Unsupported protocol in url " + url);
        return response;
    }

    if (followRedirects) {
        try {
            response.success = downloadFollowRedirects(new Request(method), response);
        } catch (SAXException e) {
            log.error("Attempting to follow redirection chain", e);
            return response;
        }
    } else {
        response.success = download(new Request(method), response);
    }

    return response;

}

From source file:org.apache.zeppelin.sap.universe.UniverseClient.java

private void setHeaders(HttpRequestBase request, String token) {
    request.setHeaders(commonHeaders);/*from   www .  ja  v  a2s .c o  m*/
    if (StringUtils.isNotBlank(token)) {
        request.addHeader(TOKEN_HEADER, token);
    }
}

From source file:com.woonoz.proxy.servlet.HttpRequestHandler.java

protected void copyHeaders(final HttpServletRequest from, final HttpRequestBase to,
        ClientHeadersHandler clientHeadersHandler) throws URISyntaxException, MalformedURLException {
    Enumeration<?> enumerationOfHeaderNames = from.getHeaderNames();
    while (enumerationOfHeaderNames.hasMoreElements()) {
        final String headerName = (String) enumerationOfHeaderNames.nextElement();
        Enumeration<?> enumerationOfHeaderValues = from.getHeaders(headerName);
        while (enumerationOfHeaderValues.hasMoreElements()) {
            final String headerValue = (String) enumerationOfHeaderValues.nextElement();
            final String modifiedValue = clientHeadersHandler.handleHeader(headerName, headerValue);
            if (modifiedValue != null) {
                to.addHeader(headerName, modifiedValue);
            }/*w  w w. j  av  a 2s  .com*/
        }
    }
}

From source file:com.okta.sdk.impl.http.httpclient.HttpClientRequestFactory.java

/**
 * Configures the headers in the specified Apache HTTP request.
 *//* w w  w .j a v  a2  s.c om*/
private void applyHeaders(HttpRequestBase httpRequest, Request request) {
    /*
     * Apache HttpClient omits the port number in the Host header (even if
     * we explicitly specify it) if it's the default port for the protocol
     * in use. To ensure that we use the same Host header in the request and
     * in the calculated string to sign (even if Apache HttpClient changed
     * and started honoring our explicit host with endpoint), we follow this
     * same behavior here and in the RequestAuthenticator.
     */
    URI endpoint = request.getResourceUrl();
    String hostHeader = endpoint.getHost();
    if (!RequestUtils.isDefaultPort(endpoint)) {
        hostHeader += ":" + endpoint.getPort();
    }
    httpRequest.addHeader("Host", hostHeader);
    httpRequest.addHeader("Accept-Encoding", "gzip");

    // Copy over any other headers already in our request
    for (Map.Entry<String, List<String>> entry : request.getHeaders().entrySet()) {
        String key = entry.getKey();
        List<String> value = entry.getValue();
        /*
         * HttpClient4 fills in the Content-Length header and complains if
         * it's already present, so we skip it here. We also skip the Host
         * header to avoid sending it twice, which will interfere with some
         * signing schemes.
         */
        if (!"Content-Length".equalsIgnoreCase(key) && !"Host".equalsIgnoreCase(key)) {
            String delimited = Strings.collectionToCommaDelimitedString(value);
            httpRequest.addHeader(key, delimited);
        }
    }
}