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.tremolosecurity.proxy.myvd.inserts.restful.OpenUnisonRestful.java

public void addAuthorizationHeader(String uri, HttpRequestBase request) throws Exception {
    LastMile lastMile = new LastMile(uri, DateTime.now().minus(30000), DateTime.now().plus(30000), 0, "");
    lastMile.getAttributes().add(this.lastMileAttribute);
    StringBuffer b = new StringBuffer();
    b.append("Bearer: ").append(lastMile.generateLastMileToken(
            GlobalEntries.getGlobalEntries().getConfigManager().getSecretKey(this.lastMileKeyName)));
    request.addHeader("Authorization", b.toString());
}

From source file:com.basho.riak.client.http.util.ClientHelper.java

/**
 * Perform and HTTP request and return the resulting response using the
 * internal HttpClient.//  w ww .  j  a v a2  s  . c  o m
 * 
 * @param bucket
 *            Bucket of the object receiving the request.
 * @param key
 *            Key of the object receiving the request or null if the request
 *            is for a bucket.
 * @param httpMethod
 *            The HTTP request to perform; must not be null.
 * @param meta
 *            Extra HTTP headers to attach to the request. Query parameters
 *            are ignored; they should have already been used to construct
 *            <code>httpMethod</code> and query parameters.
 * @param streamResponse
 *            If true, the connection will NOT be released. Use
 *            HttpResponse.getHttpMethod().getResponseBodyAsStream() to get
 *            the response stream; HttpResponse.getBody() will return null.
 * 
 * @return The HTTP response returned by Riak from executing
 *         <code>httpMethod</code>.
 * 
 * @throws RiakIORuntimeException
 *             If an error occurs during communication with the Riak server
 *             (i.e. HttpClient threw an IOException)
 */
HttpResponse executeMethod(String bucket, String key, HttpRequestBase httpMethod, RequestMeta meta,
        boolean streamResponse) {

    if (meta != null) {
        Map<String, String> headers = meta.getHeaders();
        for (String header : headers.keySet()) {
            httpMethod.addHeader(header, headers.get(header));
        }

        Map<String, String> queryParams = meta.getQueryParamMap();
        if (!queryParams.isEmpty()) {
            URI originalURI = httpMethod.getURI();
            List<NameValuePair> currentQuery = URLEncodedUtils.parse(originalURI, CharsetUtils.UTF_8.name());
            List<NameValuePair> newQuery = new LinkedList<NameValuePair>(currentQuery);

            for (Map.Entry<String, String> qp : queryParams.entrySet()) {
                newQuery.add(new BasicNameValuePair(qp.getKey(), qp.getValue()));
            }

            // For this, HC4.1 authors, I hate you
            URI newURI;
            try {
                newURI = new URIBuilder(originalURI).setQuery(URLEncodedUtils.format(newQuery, "UTF-8"))
                        .build();
            } catch (URISyntaxException e) {
                e.printStackTrace();
                throw new RiakIORuntimeException(e);
            }
            httpMethod.setURI(newURI);
        }
    }
    HttpEntity entity = null;
    try {
        org.apache.http.HttpResponse response = httpClient.execute(httpMethod);

        int status = 0;
        if (response.getStatusLine() != null) {
            status = response.getStatusLine().getStatusCode();
        }

        Map<String, String> headers = ClientUtils.asHeaderMap(response.getAllHeaders());
        byte[] body = null;
        InputStream stream = null;
        entity = response.getEntity();

        if (streamResponse) {
            stream = entity.getContent();
        } else {
            if (null != entity) {
                body = EntityUtils.toByteArray(entity);
            }
        }

        key = extractKeyFromResponseIfItWasNotAlreadyProvided(key, response);

        return new DefaultHttpResponse(bucket, key, status, headers, body, stream, response, httpMethod);
    } catch (IOException e) {
        httpMethod.abort();
        return toss(new RiakIORuntimeException(e));
    } finally {
        if (!streamResponse && entity != null) {
            try {
                EntityUtils.consume(entity);
            } catch (IOException e) {
                // NO-OP
            }
        }
    }
}

From source file:twitter4j.internal.http.ApacheHttpClientImpl.java

/**
 * sets HTTP headers/*from w ww . j av a  2s . c  o  m*/
 *
 * @param req        The request
 * @param connection HttpURLConnection
 */
private void setHeaders(HttpRequest req, HttpRequestBase connection) {
    if (logger.isDebugEnabled()) {
        logger.debug("Request: ");
        logger.debug(req.getMethod().name() + " ", req.getURL());
    }

    String authorizationHeader;
    if (req.getAuthorization() != null
            && (authorizationHeader = req.getAuthorization().getAuthorizationHeader(req)) != null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Authorization: ", z_T4JInternalStringUtil.maskString(authorizationHeader));
        }
        connection.addHeader("Authorization", authorizationHeader);
    }
    if (req.getRequestHeaders() != null) {
        for (String key : req.getRequestHeaders().keySet()) {
            connection.addHeader(key, req.getRequestHeaders().get(key));
            logger.debug(key + ": " + req.getRequestHeaders().get(key));
        }
    }
}

From source file:rawsclient.RawsClient.java

@SuppressWarnings("unchecked")
private Map<String, Object> exec_request(HttpRequestBase httpMethod)
        throws HttpResponseException, IOException, ClassCastException {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.getParams().setParameter("http.useragent", this.user_agent_name);

    BASE64Encoder enc = new sun.misc.BASE64Encoder();
    String userpassword = this.username + ":" + this.password;
    String encodedAuthorization = enc.encode(userpassword.getBytes());
    httpMethod.addHeader("Authorization", "Basic " + encodedAuthorization);

    HttpResponse response = httpClient.execute(httpMethod);
    if (response.getStatusLine().getStatusCode() > 299) {
        // try to get the reasons from the json error response
        String strErr = getReasonsFromErrorMsg(response);
        if (strErr.isEmpty()) {
            // if we can't get the reasons, dump the entire response body
            strErr = inputStreamToString(response.getEntity().getContent()).toString();
        }//from  w ww. j  a v a 2 s.c om
        throw new HttpResponseException(response.getStatusLine().getStatusCode(), strErr);
    }
    ObjectMapper mapper2 = new ObjectMapper();
    Object responseObject = mapper2.readValue(response.getEntity().getContent(), Object.class);
    httpMethod.releaseConnection();
    return (Map<String, Object>) responseObject;
}

From source file:de.m0ep.canvas.CanvasLmsRequest.java

private HttpResponse executeUnparsed() throws CanvasLmsException {
    HttpRequestBase request = null;
    try {//  w  ww  .j a v a2s.  c  o  m
        request = getMethodType().newInstance();
    } catch (InstantiationException | IllegalAccessException e) {
        throw new CanvasLmsException("Failed to create requeset method object.", e);
    }

    try {
        request.setURI(new URI(getUri()));
    } catch (URISyntaxException e) {
        throw new CanvasLmsException("Invalid uri", e);
    }

    if (null != getOauthToken()) {
        request.addHeader("Authorization", "Bearer " + getOauthToken());
    }

    if (null != getContent()) {
        // Set the content, if the request method can handle it
        if (request instanceof HttpEntityEnclosingRequest) {
            ((HttpEntityEnclosingRequest) request).setEntity(getContent());
        }
    }

    LOG.info("Send '{}' request to '{}'.", getMethodType().getSimpleName(), getUri(),
            getResponseType().getSimpleName());

    try {
        return getClient().getHttpClient().execute(request);
    } catch (IOException e) {
        throw new NetworkException("Failed to execute " + getMethodType().getSimpleName() + " request.", e);
    }
}

From source file:net.elasticgrid.rackspace.common.RackspaceConnection.java

/**
 * Make a http request and process the response. This method also performs automatic retries.
 *
 * @param request  the HTTP method to use (GET, POST, DELETE, etc)
 * @param respType the class that represents the desired/expected return type
 * @return the unmarshalled entity/*w w w.  j a  va2 s  .c o m*/
 * @throws RackspaceException
 * @throws IOException        if there is an I/O exception
 * @throws HttpException      if there is an HTTP exception
 * @throws JiBXException      if the result can't be unmarshalled
 */
@SuppressWarnings("unchecked")
protected <T> T makeRequest(HttpRequestBase request, Class<T> respType)
        throws HttpException, IOException, JiBXException, RackspaceException {

    if (!authenticated)
        authenticate();

    // add auth params, and protocol specific headers
    request.addHeader("X-Auth-Token", getAuthToken());

    // set accept and content-type headers
    request.setHeader("Accept", "application/xml; charset=UTF-8");
    request.setHeader("Accept-Encoding", "gzip");
    request.setHeader("Content-Type", "application/xml; charset=UTF-8");

    // send the request
    T result = null;
    boolean done = false;
    int retries = 0;
    boolean doRetry = false;
    RackspaceException error = null;
    do {
        HttpResponse response = null;
        if (retries > 0)
            logger.log(Level.INFO, "Retry #{0}: querying via {1} {2}",
                    new Object[] { retries, request.getMethod(), request.getURI() });
        else
            logger.log(Level.INFO, "Querying via {0} {1}",
                    new Object[] { request.getMethod(), request.getURI() });

        if (logger.isLoggable(Level.FINEST) && request instanceof HttpEntityEnclosingRequestBase) {
            HttpEntity entity = ((HttpEntityEnclosingRequestBase) request).getEntity();
            if (entity instanceof EntityTemplate) {
                EntityTemplate template = (EntityTemplate) entity;
                ByteArrayOutputStream baos = null;
                try {
                    baos = new ByteArrayOutputStream();
                    template.writeTo(baos);
                    logger.log(Level.FINEST, "Request body:\n{0}", baos.toString());
                } finally {
                    IOUtils.closeQuietly(baos);
                }
            }
        }

        InputStream entityStream = null;
        HttpEntity entity = null;

        if (logger.isLoggable(Level.FINEST)) {
            response = getHttpClient().execute(request);
            entity = response.getEntity();
            try {
                entityStream = entity.getContent();
                logger.log(Level.FINEST, "Response body on " + request.getURI() + " via " + request.getMethod()
                        + ":\n" + IOUtils.toString(entityStream));
            } finally {
                IOUtils.closeQuietly(entityStream);
            }
        }

        response = getHttpClient().execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        entity = response.getEntity();

        switch (statusCode) {
        case 200:
        case 202:
        case 203:
            try {
                entityStream = entity.getContent();
                IBindingFactory bindingFactory = BindingDirectory.getFactory(respType);
                IUnmarshallingContext unmarshallingCxt = bindingFactory.createUnmarshallingContext();
                result = (T) unmarshallingCxt.unmarshalDocument(entityStream, "UTF-8");
            } finally {
                entity.consumeContent();
                IOUtils.closeQuietly(entityStream);
            }
            done = true;
            break;
        case 503: // service unavailable
            logger.log(Level.WARNING, "Service unavailable on {0} via {1}. Will retry in {2} seconds.",
                    new Object[] { request.getURI(), request.getMethod(), Math.pow(2.0, retries + 1) });
            doRetry = true;
            break;
        case 401: // unauthorized
            logger.warning("Not authenticated or authentication token expired. Authenticating...");
            authenticate();
            doRetry = true;
            break;
        case 417:
            throw new RackspaceException(new IllegalArgumentException("Some parameters are invalid!")); // TODO: temp hack 'til Rackspace API is fixed!
        case 400:
        case 500:
        default:
            try {
                entityStream = entity.getContent();
                IBindingFactory bindingFactory = BindingDirectory.getFactory(CloudServersAPIFault.class);
                IUnmarshallingContext unmarshallingCxt = bindingFactory.createUnmarshallingContext();
                CloudServersAPIFault fault = (CloudServersAPIFault) unmarshallingCxt
                        .unmarshalDocument(entityStream, "UTF-8");
                done = true;
                throw new RackspaceException(fault.getCode(), fault.getMessage(), fault.getDetails());
            } catch (JiBXException e) {
                response = getHttpClient().execute(request);
                entity = response.getEntity();
                entityStream = entity.getContent();
                logger.log(Level.SEVERE, "Can't unmarshal response from " + request.getURI() + " via "
                        + request.getMethod() + ":" + IOUtils.toString(entityStream));
                e.printStackTrace();
                throw e;
            } finally {
                entity.consumeContent();
                IOUtils.closeQuietly(entityStream);
            }
        }

        if (doRetry) {
            retries++;
            if (retries > maxRetries) {
                throw new HttpException("Number of retries exceeded for " + request.getURI(), error);
            }
            doRetry = false;
            try {
                Thread.sleep((int) Math.pow(2.0, retries) * 1000);
            } catch (InterruptedException ex) {
                // do nothing
            }
        }
    } while (!done);

    return result;
}