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.simple.toadiot.rtinfosdk.http.DefaultRequestHandler.java

private HttpRequestBase buildRequest(HttpMethod method, String path, Map<String, String> headers, Object body,
        Map<String, Object> params) {
    AcceptedMediaType mediaType = AppConfig.getResponseMediaType();

    HttpRequestBase request = null;
    StringEntity entity = getEntity(body);
    switch (method) {
    case DELETE://from   w  ww .  j av  a2s . com
        request = new HttpDelete();
        break;
    case GET:
        request = new HttpGet();
        break;
    case POST:
        request = new HttpPost();
        if (entity != null) {
            ((HttpPost) request).setEntity(entity);
        }
        break;
    case PUT:
        request = new HttpPut();
        if (entity != null) {
            ((HttpPut) request).setEntity(entity);
        }
        break;
    default:
        return null;
    }

    try {
        if (!path.toLowerCase(Locale.ENGLISH).startsWith("http")) {
            URIBuilder uriBuilder = buildUri(method, path, params, mediaType);
            request.setURI(uriBuilder.build());
        } else {
            request.setURI(new URI(path));
        }
    } catch (URISyntaxException e) {
        throw new RequestInvalidException("Invalid URI requested.", e);
    }
    //      request.addHeader("accept", mediaType.getMediaType());
    //      request.addHeader(HEADER_KEY_API, AppConfig.getInstance().getApiKey());
    //      request.addHeader(HEADER_USER_AGENT, XIVELY_USER_AGENT);
    /**
     *  Header
     */
    request.addHeader("Content-Type", mediaType.getMediaType() + ";charset=" + AppConfig.getCharset());
    if (headers != null && !headers.isEmpty()) {
        int index = 0;
        Header[] header = new Header[headers.size()];
        for (Entry<String, String> element : headers.entrySet()) {
            header[index++] = new BasicHeader(element.getKey(), element.getValue());
        }
        request.setHeaders(header);
    }
    //      if (params != null && !params.isEmpty()) {
    //         HttpParams hparams = new SyncBasicHttpParams();
    //         for (Entry<String, Object> param : params.entrySet()) {
    //            hparams.setParameter(param.getKey(), param.getValue());
    //         }
    //         request.setParams(hparams);
    //      }
    return request;
}

From source file:com.twotoasters.android.hoot.HootTransportHttpClient.java

@Override
public HootResult synchronousExecute(HootRequest request) {

    HttpRequestBase requestBase = null;
    HootResult result = request.getResult();
    try {/*from  ww w .j a  v a  2s.co  m*/
        String uri = request.buildUri().toString();
        switch (request.getOperation()) {
        case DELETE:
            requestBase = new HttpDelete(uri);
            break;
        case GET:
            requestBase = new HttpGet(uri);
            break;
        case PUT:
            HttpPut put = new HttpPut(uri);
            put.setEntity(getEntity(request));
            requestBase = put;
            break;
        case POST:
            HttpPost post = new HttpPost(uri);
            post.setEntity(getEntity(request));
            requestBase = post;
            break;
        case HEAD:
            requestBase = new HttpHead(uri);
            break;
        }
    } catch (UnsupportedEncodingException e1) {
        result.setException(e1);
        e1.printStackTrace();
        return result;
    } catch (IOException e) {
        result.setException(e);
        e.printStackTrace();
        return result;
    }

    synchronized (mRequestBaseMap) {
        mRequestBaseMap.put(request, requestBase);
    }
    if (request.getHeaders() != null && request.getHeaders().size() > 0) {
        for (Object propertyKey : request.getHeaders().keySet()) {
            requestBase.addHeader((String) propertyKey, (String) request.getHeaders().get(propertyKey));
        }
    }

    InputStream is = null;
    try {
        Log.v(TAG, "URI: [" + requestBase.getURI().toString() + "]");
        HttpResponse response = mClient.execute(requestBase);

        if (response != null) {
            result.setResponseCode(response.getStatusLine().getStatusCode());
            Map<String, List<String>> headers = new HashMap<String, List<String>>();
            for (Header header : response.getAllHeaders()) {
                List<String> values = new ArrayList<String>();
                values.add(header.getValue());
                headers.put(header.getName(), values);
            }
            result.setHeaders(headers);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                is = entity.getContent();
                result.setResponseStream(new BufferedInputStream(is));
                request.deserializeResult();
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
        result.setException(e);
    } finally {
        requestBase = null;
        synchronized (mRequestBaseMap) {
            mRequestBaseMap.remove(request);
        }
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return result;
}

From source file:com.k42b3.neodym.oauth.Oauth.java

@SuppressWarnings("unchecked")
public void signRequest(HttpRequestBase request) throws Exception {
    // add values
    HashMap<String, String> values = new HashMap<String, String>();
    HashMap<String, String> auth;

    values.put("oauth_consumer_key", this.provider.getConsumerKey());
    values.put("oauth_token", this.token);
    values.put("oauth_signature_method", provider.getMethod());
    values.put("oauth_timestamp", this.getTimestamp());
    values.put("oauth_nonce", this.getNonce());

    auth = (HashMap<String, String>) values.clone();

    // add get vars to values
    values.putAll(parseQuery(request.getURI().getQuery()));

    // build base string
    String baseString = this.buildBaseString(request.getMethod(), request.getURI().toString(), values);

    // get signature
    SignatureInterface signature = this.getSignature();

    if (signature == null) {
        throw new Exception("Invalid signature method");
    }//  w  ww  .java  2 s  . c  o m

    // build signature
    auth.put("oauth_signature", signature.build(baseString, provider.getConsumerSecret(), this.tokenSecret));

    // add header to request
    request.addHeader("Authorization", "OAuth realm=\"neodym\", " + this.buildAuthString(auth));
}

From source file:com.ibm.sbt.services.client.ClientService.java

protected void addHeaders(HttpClient httpClient, HttpRequestBase httpRequestBase, Args args) {
    for (Map.Entry<String, String> e : args.getHeaders().entrySet()) {
        String headerName = e.getKey();
        String headerValue = e.getValue();
        httpRequestBase.addHeader(headerName, headerValue);
    }/*w ww . jav  a  2  s. c o  m*/
}

From source file:com.google.acre.servlet.ProxyPassServlet.java

/**
 * Retreives all of the headers from the servlet request and sets them on
 * the proxy request/*from   ww w.  j a  va  2s  .c  o  m*/
 * 
 * @param httpServletRequest The request object representing the client's
 *                            request to the servlet engine
 * @param httpMethodProxyRequest The request that we are about to send to
 *                                the proxy host
 */
private void setProxyRequestHeaders(HttpServletRequest httpServletRequest,
        HttpRequestBase httpMethodProxyRequest) {
    // Get an Enumeration of all of the header names sent by the client
    Enumeration<?> enumerationOfHeaderNames = httpServletRequest.getHeaderNames();
    while (enumerationOfHeaderNames.hasMoreElements()) {
        String stringHeaderName = (String) enumerationOfHeaderNames.nextElement();
        if (stringHeaderName.equalsIgnoreCase(STRING_CONTENT_LENGTH_HEADER_NAME))
            continue;
        // As per the Java Servlet API 2.5 documentation:
        //      Some headers, such as Accept-Language can be sent by clients
        //      as several headers each with a different value rather than
        //      sending the header as a comma separated list.
        // Thus, we get an Enumeration of the header values sent by the client
        Enumeration<?> enumerationOfHeaderValues = httpServletRequest.getHeaders(stringHeaderName);
        while (enumerationOfHeaderValues.hasMoreElements()) {
            String stringHeaderValue = (String) enumerationOfHeaderValues.nextElement();
            // In case the proxy host is running multiple virtual servers,
            // rewrite the Host header to ensure that we get content from
            // the correct virtual server
            if (stringHeaderName.equalsIgnoreCase(STRING_HOST_HEADER_NAME)) {
                stringHeaderValue = this.metawebAPIHostAndPort;
            }
            // Set the same header on the proxy request
            httpMethodProxyRequest.addHeader(stringHeaderName, stringHeaderValue);
        }
    }
}

From source file:net.community.chest.gitcloud.facade.frontend.git.GitController.java

private Map<String, String> copyRequestHeadersValues(HttpServletRequest req, HttpRequestBase request) {
    Map<String, String> hdrsMap = ServletUtils.getRequestHeaders(req);
    for (Map.Entry<String, String> hdrEntry : hdrsMap.entrySet()) {
        String hdrName = hdrEntry.getKey(), hdrValue = StringUtils.trimToEmpty(hdrEntry.getValue());
        if (StringUtils.isEmpty(hdrValue)) {
            logger.warn("copyRequestHeadersValues(" + req.getMethod() + ")[" + req.getRequestURI() + "]["
                    + req.getQueryString() + "]" + " no value for header " + hdrName);

        }//from www. jav  a 2  s  .c o  m

        if (FILTERED_REQUEST_HEADERS.contains(hdrName)) {
            if (logger.isTraceEnabled()) {
                logger.trace("copyRequestHeadersValues(" + req.getMethod() + ")[" + req.getRequestURI() + "]["
                        + req.getQueryString() + "]" + " filtered " + hdrName + ": " + hdrValue);
            }
        } else {
            if (logger.isTraceEnabled()) {
                logger.trace("copyRequestHeadersValues(" + req.getMethod() + ")[" + req.getRequestURI() + "]["
                        + req.getQueryString() + "]" + " " + hdrName + ": " + hdrValue);
            }
            request.addHeader(hdrName, hdrValue);
        }

        hdrsMap.put(hdrName, hdrValue);
    }

    return hdrsMap;
}

From source file:com.streamreduce.AbstractInContainerTestCase.java

/**
 * Makes a request to the given url using the given method and possibly submitting
 * the given data.  If you need the request to be an authenticated request, pass in
 * your authentication token as well./*from  ww w .j  a v  a  2 s.  co m*/
 *
 * @param url        the url for the request
 * @param method     the method to use for the request
 * @param data       the data, if any, for the request
 * @param authnToken the token retrieved during authentication
 * @param type       API or GATEWAY, tells us the auth token key to use
 * @return the response as string (This is either the response payload or the status code if no payload is sent)
 * @throws Exception if something goes wrong
 */
public String makeRequest(String url, String method, Object data, String authnToken, AuthTokenType type)
        throws Exception {
    HttpClient httpClient = new DefaultHttpClient();
    HttpRequestBase request;
    String actualPayload;

    // Set the User-Agent to be safe
    httpClient.getParams().setParameter(HttpProtocolParams.USER_AGENT, Constants.NODEABLE_HTTP_USER_AGENT);

    // Create the request object
    if (method.equals("DELETE")) {
        request = new HttpDelete(url);
    } else if (method.equals("GET")) {
        request = new HttpGet(url);
    } else if (method.equals("POST")) {
        request = new HttpPost(url);
    } else if (method.equals("PUT")) {
        request = new HttpPut(url);
    } else if (method.equals("HEAD")) {
        request = new HttpHead(url);
    } else {
        throw new IllegalArgumentException("The method you specified is not supported.");
    }

    // Put data into the request for POST and PUT requests
    if (method.equals("POST") || method.equals("PUT")) {
        HttpEntityEnclosingRequestBase eeMethod = (HttpEntityEnclosingRequestBase) request;
        String requestBody = data instanceof JSONObject ? ((JSONObject) data).toString()
                : new ObjectMapper().writeValueAsString(data);

        eeMethod.setEntity(new StringEntity(requestBody, MediaType.APPLICATION_JSON, "UTF-8"));
    }

    // Add the authentication token to the request
    if (authnToken != null) {
        if (type.equals(AuthTokenType.API)) {
            request.addHeader(Constants.NODEABLE_AUTH_TOKEN, authnToken);
        } else if (type.equals(AuthTokenType.GATEWAY)) {
            request.addHeader(Constants.NODEABLE_API_KEY, authnToken);
        } else {
            throw new Exception("Unsupported Type of  " + type + " for authToken " + authnToken);
        }

    }

    // Execute the request
    try {
        HttpResponse response = httpClient.execute(request);
        String payload = IOUtils.toString(response.getEntity().getContent());

        // To work around HEAD, where we cannot receive a payload, and other scenarios where the payload could
        // be empty, let's stuff the response status code into the response.
        actualPayload = payload != null && payload.length() > 0 ? payload
                : Integer.toString(response.getStatusLine().getStatusCode());
    } finally {
        request.releaseConnection();
    }

    return actualPayload;
}

From source file:org.opendaylight.infrautils.diagstatus.shell.HttpClient.java

public HttpResponse sendRequest(HttpRequest request) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    if (httpclient == null) {
        throw new ClientProtocolException("Couldn't create an HTTP client");
    }//from   w w  w .j a v a 2  s .c o  m
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(request.getTimeout())
            .setConnectTimeout(request.getTimeout()).build();
    HttpRequestBase httprequest;
    String method = request.getMethod();
    if (method.equalsIgnoreCase("GET")) {
        httprequest = new HttpGet(request.getUri());
    } else if (method.equalsIgnoreCase("POST")) {
        httprequest = new HttpPost(request.getUri());
        if (request.getEntity() != null) {
            StringEntity sentEntity = new StringEntity(request.getEntity());
            sentEntity.setContentType(request.getContentType());
            ((HttpEntityEnclosingRequestBase) httprequest).setEntity(sentEntity);
        }
    } else if (method.equalsIgnoreCase("PUT")) {
        httprequest = new HttpPut(request.getUri());
        if (request.getEntity() != null) {
            StringEntity sentEntity = new StringEntity(request.getEntity());
            sentEntity.setContentType(request.getContentType());
            ((HttpEntityEnclosingRequestBase) httprequest).setEntity(sentEntity);
        }
    } else if (method.equalsIgnoreCase("DELETE")) {
        httprequest = new HttpDelete(request.getUri());
    } else {
        httpclient.close();
        throw new IllegalArgumentException(
                "This profile class only supports GET, POST, PUT, and DELETE methods");
    }
    httprequest.setConfig(requestConfig);
    // add request headers
    Iterator<String> headerIterator = request.getHeaders().keySet().iterator();
    while (headerIterator.hasNext()) {
        String header = headerIterator.next();
        Iterator<String> valueIterator = request.getHeaders().get(header).iterator();
        while (valueIterator.hasNext()) {
            httprequest.addHeader(header, valueIterator.next());
        }
    }
    CloseableHttpResponse response = httpclient.execute(httprequest);
    try {
        int httpResponseCode = response.getStatusLine().getStatusCode();
        HashMap<String, List<String>> headerMap = new HashMap<>();
        // copy response headers
        HeaderIterator it = response.headerIterator();
        while (it.hasNext()) {
            Header nextHeader = it.nextHeader();
            String name = nextHeader.getName();
            String value = nextHeader.getValue();
            if (headerMap.containsKey(name)) {
                headerMap.get(name).add(value);
            } else {
                List<String> list = new ArrayList<>();
                list.add(value);
                headerMap.put(name, list);
            }
        }
        if (httpResponseCode > 299) {
            return new HttpResponse(httpResponseCode, response.getStatusLine().getReasonPhrase(), headerMap);
        }
        Optional<HttpEntity> receivedEntity = Optional.ofNullable(response.getEntity());
        String httpBody = receivedEntity.isPresent() ? EntityUtils.toString(receivedEntity.get()) : null;
        return new HttpResponse(response.getStatusLine().getStatusCode(), httpBody, headerMap);
    } finally {
        response.close();
    }
}

From source file:com.baidubce.http.BceHttpClient.java

/**
 * Creates HttpClient method object based on the specified request and
 * populates any parameters, headers, etc. from the internal request.
 *
 * @param request The request to convert to an HttpClient method object.
 * @return The converted HttpClient method object with any parameters, headers, etc. from the original request set.
 *///from  ww w  .ja  v a 2  s.  c  o m
protected HttpRequestBase createHttpRequest(InternalRequest request) {
    String uri = request.getUri().toASCIIString();
    String encodedParams = HttpUtils.getCanonicalQueryString(request.getParameters(), false);

    if (encodedParams.length() > 0) {
        uri += "?" + encodedParams;
    }

    HttpRequestBase httpRequest;
    long contentLength = -1;
    String contentLengthString = request.getHeaders().get(Headers.CONTENT_LENGTH);
    if (contentLengthString != null) {
        contentLength = Long.parseLong(contentLengthString);
    }
    if (request.getHttpMethod() == HttpMethodName.GET) {
        httpRequest = new HttpGet(uri);
    } else if (request.getHttpMethod() == HttpMethodName.PUT) {
        HttpPut putMethod = new HttpPut(uri);
        httpRequest = putMethod;
        if (request.getContent() != null) {
            putMethod.setEntity(new InputStreamEntity(request.getContent(), contentLength));
        }
    } else if (request.getHttpMethod() == HttpMethodName.POST) {
        HttpPost postMethod = new HttpPost(uri);
        httpRequest = postMethod;
        if (request.getContent() != null) {
            postMethod.setEntity(new InputStreamEntity(request.getContent(), contentLength));
        }
    } else if (request.getHttpMethod() == HttpMethodName.DELETE) {
        httpRequest = new HttpDelete(uri);
    } else if (request.getHttpMethod() == HttpMethodName.HEAD) {
        httpRequest = new HttpHead(uri);
    } else {
        throw new BceClientException("Unknown HTTP method name: " + request.getHttpMethod());
    }

    httpRequest.addHeader(Headers.HOST, HttpUtils.generateHostHeader(request.getUri()));

    // Copy over any other headers already in our request
    for (Entry<String, String> entry : request.getHeaders().entrySet()) {
        /*
         * 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 (entry.getKey().equalsIgnoreCase(Headers.CONTENT_LENGTH)
                || entry.getKey().equalsIgnoreCase(Headers.HOST)) {
            continue;
        }

        httpRequest.addHeader(entry.getKey(), entry.getValue());
    }

    checkNotNull(httpRequest.getFirstHeader(Headers.CONTENT_TYPE), Headers.CONTENT_TYPE + " not set");
    return httpRequest;
}

From source file:com.ibm.sbt.service.basic.ProxyService.java

@SuppressWarnings("unchecked")
protected boolean prepareForwardingHeaders(HttpRequestBase method, HttpServletRequest request)
        throws ServletException {
    Object timedObject = ProxyProfiler.getTimedObject();
    // Forward any headers that should be forwarded. Except cookies.
    StringBuffer xForwardedForHeader = new StringBuffer();
    for (Enumeration<String> e = request.getHeaderNames(); e.hasMoreElements();) {
        String headerName = e.nextElement();
        // Ignore cookie - treat them separately
        if (headerName.equalsIgnoreCase("cookie")) { // $NON-NLS-1$
            continue;
        }//from w  w  w . ja  v  a2  s  .  c  o m
        String headerValue = request.getHeader(headerName);
        // This is to be investigated - Should the X-Forwarded-For being passed? Ryan.
        //            if(headerName.equalsIgnoreCase("X-Forwarded-For") || headerName.equalsIgnoreCase("host")) {
        //                addXForwardedForHeader(method, headerValue, xForwardedForHeader);
        //                continue;
        //            }
        // Ensure that the header is allowed
        if (isHeaderAllowed(headerName)) {
            method.addHeader(headerName, headerValue);
            if (getDebugHook() != null) {
                getDebugHook().getDumpRequest().addHeader(headerName, headerValue);
            }
        }
    }
    String xForward = xForwardedForHeader.toString();
    if (StringUtil.isNotEmpty(xForward)) {
        method.addHeader("X-Forwarded-For", xForward);
        if (getDebugHook() != null) {
            getDebugHook().getDumpRequest().addHeader("X-Forwarded-For", xForward);
        }
    }
    ProxyProfiler.profileTimedRequest(timedObject, "prepareForwardingHeaders");
    return true;
}