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.reachcall.pretty.http.ProxyServlet.java

@SuppressWarnings("unchecked")
public void copyHeaders(HttpServletRequest req, HttpRequestBase method) {
    Enumeration names = req.getHeaderNames();

    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();

        if (name.equalsIgnoreCase(HEADER_CONTENT_LENTH)) {
            continue;
        }/*from w  ww  .j a va2s. c  om*/

        Enumeration values = req.getHeaders(name);

        while (values.hasMoreElements()) {
            String value = (String) values.nextElement();
            LOG.log(Level.FINER, "{0} : {1}", new Object[] { name, value });

            if (name.equalsIgnoreCase(HEADER_HOST) || name.equalsIgnoreCase(HEADER_X_FORWARDED_FOR)) {
                continue;
            } else {
                method.addHeader(name, value);
            }
        }

        setVHost(req.getHeader("Host"));
    }
    method.addHeader(HEADER_REMOTE_HOST, req.getRemoteAddr());
    String xff = req.getHeader(HEADER_X_FORWARDED_FOR);

    if (xff == null) {
        xff = "";
    } else {
        xff = xff + ", ";
    }

    method.addHeader(HEADER_X_FORWARDED_FOR, xff + req.getRemoteHost());

    if (req.getHeader(HEADER_X_ORIGINAL_REQUEST_URL) == null) {
        method.addHeader(HEADER_X_ORIGINAL_REQUEST_URL, req.getRequestURL().toString());
    }
}

From source file:org.apache.wink.client.internal.handlers.httpclient.ApacheHttpClientConnectionHandler.java

private HttpRequestBase setupHttpRequest(ClientRequest request, HttpClient client, EntityWriter entityWriter) {
    URI uri = request.getURI();// w w  w  .  j a  v  a  2  s  .c o m
    String method = request.getMethod();
    HttpRequestBase httpRequest = null;
    if (entityWriter == null) {
        GenericHttpRequestBase entityRequest = new GenericHttpRequestBase(method);
        httpRequest = entityRequest;
    } else {
        // create a new request with the specified method
        HttpEntityEnclosingRequestBase entityRequest = new GenericHttpEntityEnclosingRequestBase(method);
        entityRequest.setEntity(entityWriter);
        httpRequest = entityRequest;
    }
    // set the uri
    httpRequest.setURI(uri);
    // add all headers
    MultivaluedMap<String, String> headers = request.getHeaders();
    for (String header : headers.keySet()) {
        List<String> values = headers.get(header);
        for (String value : values) {
            if (value != null) {
                httpRequest.addHeader(header, value);
            }
        }
    }
    return httpRequest;
}

From source file:com.cloudbees.eclipse.core.JenkinsService.java

synchronized private Object retrieveWithLogin(final DefaultHttpClient httpclient, final HttpRequestBase post,
        final List<NameValuePair> params, final boolean expectRedirect, final SubProgressMonitor monitor,
        final ResponseType responseType) throws UnsupportedEncodingException, IOException,
        ClientProtocolException, CloudBeesException, Exception {
    Object bodyResponse = null;/*from  www . ja v  a  2  s  .  c om*/

    if (this.jenkins.username != null && this.jenkins.username.trim().length() > 0
            && this.jenkins.password != null && this.jenkins.password.trim().length() > 0) {
        post.addHeader("Authorization",
                "Basic " + Utils.toB64(this.jenkins.username + ":" + this.jenkins.password));
    }

    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    if (params != null) {
        nvps.addAll(params);
    }

    if (post instanceof HttpEntityEnclosingRequest) {
        if (((HttpEntityEnclosingRequest) post).getEntity() == null) {
            ((HttpEntityEnclosingRequest) post).setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        }
    }

    //CloudBeesCorePlugin.getDefault().getLogger().info("Jenkins request: " + post.getURI());

    if (post instanceof HttpPost) {
        HttpPost pp = (HttpPost) post;

        String s;
        try {
            s = new Scanner(pp.getEntity().getContent()).useDelimiter("\\A").next();
        } catch (java.util.NoSuchElementException e) {
            s = "";
        }

        //CloudBeesCorePlugin.getDefault().getLogger().info("Jenkins request post params: " + s);

    }

    HttpResponse resp = httpclient.execute(post);
    switch (responseType) {
    case STRING:
        bodyResponse = Utils.getResponseBody(resp);
        break;
    case STREAM:
        bodyResponse = resp.getEntity().getContent();
        break;
    case HTTP:
        bodyResponse = resp;
        break;
    }

    Utils.checkResponseCode(resp, expectRedirect, jenkins.atCloud);

    return bodyResponse;
}

From source file:com.robustaweb.library.rest.client.implementation.AndroidRestClient.java

/**
 * {@inheritDoc }//  ww  w . j  a va2  s  .  c o m
 */
@Override
protected void executeMethod(final HttpMethod method, final String url, final String requestBody,
        final Callback callback) throws HttpException {

    requestThread = new Thread() {

        @Override
        public void run() {

            HttpRequestBase meth = null;
            try {
                switch (method) {
                case GET:
                    meth = new HttpGet(url);

                    break;
                case POST:
                    meth = new HttpPost(url);
                    break;
                case DELETE:
                    meth = new HttpDelete(url);
                    break;
                case PUT:
                    meth = new HttpPut(url);
                    break;
                default:
                    meth = new HttpEntityEnclosingRequestBase() {
                        @Override
                        public String getMethod() {
                            return method.getMethod();
                        }
                    };
                    break;
                }
                // this.builder = new RequestBuilder(meth, url);

                if (contentType != null && !contentType.isEmpty()) {

                    meth.addHeader("Content-Type", contentType);
                }
                if (AndroidRestClient.authorizationValue != null
                        && AndroidRestClient.authorizationValue.length() > 0) {
                    meth.addHeader("Authorization", AndroidRestClient.authorizationValue);
                }

                HttpContext localContext = new BasicHttpContext();
                HttpResponse response = client.execute(meth, localContext);
                callback.onSuccess(response.toString());

                // headers response
                HeaderIterator it = response.headerIterator();
                while (it.hasNext()) {
                    Header header = it.nextHeader();
                    responseHeaders.put(header.getName(), header.getValue());
                }

            } catch (Exception ex) {
                callback.onException(ex);
            } finally {
                clean();
            }
        }
    };
}

From source file:org.apache.axis2.transport.http.impl.httpclient4.HTTPSenderImpl.java

protected HttpResponse executeMethod(AbstractHttpClient httpClient, MessageContext msgContext, URL url,
        HttpRequestBase method) throws IOException {
    HttpHost httpHost = this.getHostConfiguration(httpClient, msgContext, url);

    // set the custom headers, if available
    addCustomHeaders(method, msgContext);

    // add compression headers if needed
    if (msgContext.isPropertyTrue(HTTPConstants.MC_ACCEPT_GZIP)) {
        method.addHeader(HTTPConstants.HEADER_ACCEPT_ENCODING, HTTPConstants.COMPRESSION_GZIP);
    }//from   ww  w. java  2 s. c  om

    if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
        method.addHeader(HTTPConstants.HEADER_CONTENT_ENCODING, HTTPConstants.COMPRESSION_GZIP);
    }

    if (msgContext.getProperty(HTTPConstants.HTTP_METHOD_PARAMS) != null) {
        HttpParams params = (HttpParams) msgContext.getProperty(HTTPConstants.HTTP_METHOD_PARAMS);
        method.setParams(params);
    }

    String cookiePolicy = (String) msgContext.getProperty(HTTPConstants.COOKIE_POLICY);
    if (cookiePolicy != null) {
        method.getParams().setParameter(ClientPNames.COOKIE_POLICY, cookiePolicy);
    }

    setTimeouts(msgContext, method);
    HttpContext localContext = new BasicHttpContext();
    // Why do we have add context here
    return httpClient.execute(httpHost, method, localContext);
}

From source file:net.tirasa.wink.client.asynchttpclient.ApacheHttpAsyncClientConnectionHandler.java

private HttpRequestBase setupHttpRequest(ClientRequest request,
        ApacheHttpAsyncClientConnectionHandler.EntityWriter entityWriter) {

    URI uri = request.getURI();//  w w  w  .  ja va2 s.  com
    String method = request.getMethod();
    HttpRequestBase httpRequest;
    if (entityWriter == null) {
        GenericHttpRequestBase entityRequest = new GenericHttpRequestBase(method);
        httpRequest = entityRequest;
    } else {
        // create a new request with the specified method
        HttpEntityEnclosingRequestBase entityRequest = new ApacheHttpAsyncClientConnectionHandler.GenericHttpEntityEnclosingRequestBase(
                method);
        entityRequest.setEntity(entityWriter);
        httpRequest = entityRequest;
    }
    // set the uri
    httpRequest.setURI(uri);
    // add all headers
    MultivaluedMap<String, String> headers = request.getHeaders();
    for (String header : headers.keySet()) {
        List<String> values = headers.get(header);
        for (String value : values) {
            if (value != null) {
                httpRequest.addHeader(header, value);
            }
        }
    }
    return httpRequest;
}

From source file:org.apache.ignite.console.agent.handlers.RestHandler.java

/**
 * @param uri Url./*from ww w  .  j ava 2  s .co  m*/
 * @param params Params.
 * @param demo Use demo node.
 * @param mtd Method.
 * @param headers Headers.
 * @param body Body.
 */
protected RestResult executeRest(String uri, Map<String, Object> params, boolean demo, String mtd,
        Map<String, Object> headers, String body) throws IOException, URISyntaxException {
    if (log.isDebugEnabled())
        log.debug("Start execute REST command [method=" + mtd + ", uri=/" + (uri == null ? "" : uri)
                + ", parameters=" + params + "]");

    final URIBuilder builder;

    if (demo) {
        // try start demo if needed.
        AgentClusterDemo.testDrive(cfg);

        // null if demo node not started yet.
        if (cfg.demoNodeUri() == null)
            return RestResult.fail("Demo node is not started yet.", 404);

        builder = new URIBuilder(cfg.demoNodeUri());
    } else
        builder = new URIBuilder(cfg.nodeUri());

    if (builder.getPort() == -1)
        builder.setPort(DFLT_NODE_PORT);

    if (uri != null) {
        if (!uri.startsWith("/") && !cfg.nodeUri().endsWith("/"))
            uri = '/' + uri;

        builder.setPath(uri);
    }

    if (params != null) {
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            if (entry.getValue() != null)
                builder.addParameter(entry.getKey(), entry.getValue().toString());
        }
    }

    HttpRequestBase httpReq = null;

    try {
        if ("GET".equalsIgnoreCase(mtd))
            httpReq = new HttpGet(builder.build());
        else if ("POST".equalsIgnoreCase(mtd)) {
            HttpPost post;

            if (body == null) {
                List<NameValuePair> nvps = builder.getQueryParams();

                builder.clearParameters();

                post = new HttpPost(builder.build());

                if (!nvps.isEmpty())
                    post.setEntity(new UrlEncodedFormEntity(nvps));
            } else {
                post = new HttpPost(builder.build());

                post.setEntity(new StringEntity(body));
            }

            httpReq = post;
        } else
            throw new IOException("Unknown HTTP-method: " + mtd);

        if (headers != null) {
            for (Map.Entry<String, Object> entry : headers.entrySet())
                httpReq.addHeader(entry.getKey(),
                        entry.getValue() == null ? null : entry.getValue().toString());
        }

        try (CloseableHttpResponse resp = httpClient.execute(httpReq)) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();

            resp.getEntity().writeTo(out);

            Charset charset = Charsets.UTF_8;

            Header encodingHdr = resp.getEntity().getContentEncoding();

            if (encodingHdr != null) {
                String encoding = encodingHdr.getValue();

                charset = Charsets.toCharset(encoding);
            }

            return RestResult.success(resp.getStatusLine().getStatusCode(),
                    new String(out.toByteArray(), charset));
        } catch (ConnectException e) {
            log.info("Failed connect to node and execute REST command [uri=" + builder.build() + "]");

            return RestResult.fail("Failed connect to node and execute REST command.", 404);
        }
    } finally {
        if (httpReq != null)
            httpReq.reset();
    }
}

From source file:org.dasein.cloud.azure.AzureMethod.java

public void tempRedirectInvoke(@Nonnull String tempEndpoint, @Nonnull String method, @Nonnull String account,
        @Nonnull String resource, @Nonnull String body) throws CloudException, InternalException {
    if (logger.isTraceEnabled()) {
        logger.trace("enter - " + AzureMethod.class.getName() + ".post(" + account + "," + resource + ")");
    }/* ww  w  . ja v  a2 s. co  m*/
    if (wire.isDebugEnabled()) {
        wire.debug("POST --------------------------------------------------------> " + endpoint + account
                + resource);
        wire.debug("");
    }
    try {
        HttpClient client = getClient();
        String url = tempEndpoint + account + resource;

        HttpRequestBase httpMethod = getMethod(method, url);

        //If it is networking configuration services
        if (httpMethod instanceof HttpPut) {
            if (url.endsWith("/services/networking/media")) {
                httpMethod.addHeader("Content-Type", "text/plain");
            } else {
                httpMethod.addHeader("Content-Type", "application/xml;charset=UTF-8");
            }
        } else {
            httpMethod.addHeader("Content-Type", "application/xml;charset=UTF-8");
        }

        //dmayne version is older for anything to do with images and for disk deletion
        if (url.indexOf("/services/images") > -1
                || (httpMethod instanceof HttpDelete && url.indexOf("/services/disks") > -1)) {
            httpMethod.addHeader("x-ms-version", "2012-08-01");
        } else {
            httpMethod.addHeader("x-ms-version", "2012-03-01");
        }
        if (wire.isDebugEnabled()) {
            wire.debug(httpMethod.getRequestLine().toString());
            for (Header header : httpMethod.getAllHeaders()) {
                wire.debug(header.getName() + ": " + header.getValue());
            }
            wire.debug("");
            if (body != null) {
                wire.debug(body);
                wire.debug("");
            }
        }

        if (httpMethod instanceof HttpEntityEnclosingRequestBase) {

            HttpEntityEnclosingRequestBase entityEnclosingMethod = (HttpEntityEnclosingRequestBase) httpMethod;

            if (body != null) {
                try {
                    entityEnclosingMethod.setEntity(new StringEntity(body, "application/xml", "utf-8"));
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

        HttpResponse response;
        StatusLine status;

        try {
            response = client.execute(httpMethod);
            status = response.getStatusLine();
        } catch (IOException e) {
            logger.error("post(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage());
            if (logger.isTraceEnabled()) {
                e.printStackTrace();
            }
            throw new CloudException(e);
        }
        if (logger.isDebugEnabled()) {
            logger.debug("post(): HTTP Status " + status);
        }
        Header[] headers = response.getAllHeaders();

        if (wire.isDebugEnabled()) {
            wire.debug(status.toString());
            for (Header h : headers) {
                if (h.getValue() != null) {
                    wire.debug(h.getName() + ": " + h.getValue().trim());
                } else {
                    wire.debug(h.getName() + ":");
                }
            }
            wire.debug("");
        }
        if (status.getStatusCode() != HttpServletResponse.SC_OK
                && status.getStatusCode() != HttpServletResponse.SC_CREATED
                && status.getStatusCode() != HttpServletResponse.SC_ACCEPTED) {
            logger.error("post(): Expected OK for GET request, got " + status.getStatusCode());

            HttpEntity entity = response.getEntity();

            if (entity == null) {
                throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(),
                        status.getReasonPhrase(), "An error was returned without explanation");
            }
            try {
                body = EntityUtils.toString(entity);
            } catch (IOException e) {
                throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(),
                        status.getReasonPhrase(), e.getMessage());
            }
            if (wire.isDebugEnabled()) {
                wire.debug(body);
            }
            wire.debug("");
            AzureException.ExceptionItems items = AzureException.parseException(status.getStatusCode(), body);

            if (items == null) {
                throw new CloudException(CloudErrorType.GENERAL, status.getStatusCode(), "Unknown", "Unknown");
            }
            logger.error("post(): [" + status.getStatusCode() + " : " + items.message + "] " + items.details);
            throw new AzureException(items);
        }
    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace("exit - " + AzureMethod.class.getName() + ".post()");
        }
        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug("POST --------------------------------------------------------> " + endpoint + account
                    + resource);
        }
    }
}