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:org.wso2.carbon.identity.mgt.endpoint.client.SelfRegistrationMgtClient.java

/**
 * adding OAuth authorization headers to a httpMethod
 *
 * @param httpMethod method which wants to add Authorization header
 *///w  w w  . ja v a 2 s .  c om
private void setAuthorizationHeader(HttpRequestBase httpMethod) {

    String toEncode = IdentityManagementServiceUtil.getInstance().getAppName() + ":"
            + String.valueOf(IdentityManagementServiceUtil.getInstance().getAppPassword());
    byte[] encoding = Base64.encodeBase64(toEncode.getBytes());
    String authHeader = new String(encoding, Charset.defaultCharset());
    httpMethod.addHeader(HTTPConstants.HEADER_AUTHORIZATION, CLIENT + authHeader);

}

From source file:net.netheos.pcsapi.providers.hubic.Swift.java

private void configureSession(HttpRequestBase request, String format) {
    request.addHeader("X-Auth-token", authToken);
    if (format != null) {
        try {//from ww w. j a v a  2  s  .com
            URI uri = request.getURI();
            if (uri.getRawQuery() != null) {
                request.setURI(URI.create(uri + "&format=" + URLEncoder.encode(format, "UTF-8")));
            } else {
                request.setURI(URI.create(uri + "?format=" + URLEncoder.encode(format, "UTF-8")));
            }

        } catch (UnsupportedEncodingException ex) {
            throw new UnsupportedOperationException("Error setting the request format", ex);
        }
    }
}

From source file:org.sonatype.nexus.repository.proxy.ProxyFacetSupport.java

protected Content fetch(String url, Context context, @Nullable Content stale) throws IOException {
    HttpClient client = httpClient.getHttpClient();

    checkState(config.remoteUrl.isAbsolute(),
            "Invalid remote URL '%s' for proxy repository %s, please fix your configuration", config.remoteUrl,
            getRepository().getName());/*from   w ww  .  j av  a2s  . c o m*/
    URI uri;
    try {
        uri = config.remoteUrl.resolve(url);
    } catch (IllegalArgumentException e) { // NOSONAR
        log.warn("Unable to resolve url. Reason: {}", e.getMessage());
        throw new BadRequestException("Invalid repository path");
    }
    HttpRequestBase request = buildFetchHttpRequest(uri, context);
    if (stale != null) {
        final DateTime lastModified = stale.getAttributes().get(Content.CONTENT_LAST_MODIFIED, DateTime.class);
        if (lastModified != null) {
            request.addHeader(HttpHeaders.IF_MODIFIED_SINCE, DateUtils.formatDate(lastModified.toDate()));
        }
        final String etag = stale.getAttributes().get(Content.CONTENT_ETAG, String.class);
        if (etag != null) {
            request.addHeader(HttpHeaders.IF_NONE_MATCH, "\"" + etag + "\"");
        }
    }
    log.debug("Fetching: {}", request);

    HttpResponse response = execute(context, client, request);
    log.debug("Response: {}", response);

    StatusLine status = response.getStatusLine();
    log.debug("Status: {}", status);

    final CacheInfo cacheInfo = getCacheController(context).current();

    if (status.getStatusCode() == HttpStatus.SC_OK) {
        HttpEntity entity = response.getEntity();
        log.debug("Entity: {}", entity);

        final Content result = createContent(context, response);
        result.getAttributes().set(Content.CONTENT_LAST_MODIFIED, extractLastModified(request, response));
        result.getAttributes().set(Content.CONTENT_ETAG, extractETag(response));
        result.getAttributes().set(CacheInfo.class, cacheInfo);
        return result;
    }

    try {
        if (status.getStatusCode() == HttpStatus.SC_NOT_MODIFIED) {
            checkState(stale != null, "Received 304 without conditional GET (bad server?) from %s", uri);
            indicateVerified(context, stale, cacheInfo);
        }
        mayThrowProxyServiceException(response);
    } finally {
        HttpClientUtils.closeQuietly(response);
    }

    return null;
}

From source file:org.wso2.carbon.bpmn.extensions.rest.RESTInvoker.java

private void processHeaderList(HttpRequestBase request, JsonNodeObject jsonHeaders) {
    if (jsonHeaders != null) {
        Iterator<String> iterator = jsonHeaders.fieldNames();
        while (iterator.hasNext()) {
            String key = iterator.next();
            String value = jsonHeaders.findValue(key).textValue();
            request.addHeader(key, value);
        }/*from  w  w  w  .  ja  v  a 2 s .c o m*/
    }
}

From source file:org.hardisonbrewing.s3j.FileSyncer.java

private void addHeaders(HttpRequestBase httpRequest, String path) throws Exception {

    long expires = System.currentTimeMillis() + (1000 * 60);

    httpRequest.addHeader("Host", bucket + ".s3.amazonaws.com");
    httpRequest.addHeader("x-amz-date", amzDateFormat(expires));

    String resource = "/" + bucket + "/";
    if (path != null && path.length() > 0) {
        resource += path;//from   w  w  w  .j  a v  a 2s . c o m
    }
    String signature = signature(accessKey, expires, resource, httpRequest);
    httpRequest.addHeader("Authorization", "AWS " + accessKeyId + ":" + signature);

}

From source file:com.swisscom.refimpl.boundary.MIB2Client.java

private void addSignature(HttpRequestBase request, String methodByName, String path, String merchantId,
        String contentType, byte[] data) {
    RequestSignInformations reqSign = new RequestSignInformations();
    reqSign.setDate(RFC_822_DATE_FORMAT_TZ_GMT.format(new Date()));
    reqSign.setMethod(methodByName);/*from w  ww. j ava 2  s.  co m*/
    reqSign.setPath(path);
    reqSign.setData(data);
    reqSign.setContentType(contentType);

    if (merchantId != null) {
        request.addHeader("x-merchant-id", merchantId);
    }

    String sig;
    try {
        sig = new Signer().buildSignature(reqSign, Constants.SEC_KEY);
        request.addHeader("x-scs-signature", sig);
        request.addHeader("x-scs-date", reqSign.getDate());
        if (data != null) {
            request.addHeader("content-md5", new String(Base64.encodeBase64(DigestUtils.md5(data))));
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.duracloud.common.web.RestHttpHelper.java

private void addHeaders(HttpRequestBase httpRequest, Map<String, String> headers) {
    Iterator<String> headerIt = headers.keySet().iterator();
    while (headerIt.hasNext()) {
        String headerName = headerIt.next();
        String headerValue = headers.get(headerName);
        if (headerName != null && headerValue != null) {
            httpRequest.addHeader(headerName, headerValue);
        }/*  w ww. ja  v a2  s  .co  m*/
    }
}

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

/**
 * Perform and HTTP request and return the resulting response using the
 * internal HttpClient.//from   www .  j  av a2 s  . c om
 * 
 * @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 = URIUtils.createURI(originalURI.getScheme(), originalURI.getHost(),
                        originalURI.getPort(), originalURI.getPath(), URLEncodedUtils.format(newQuery, "UTF-8"),
                        null);
            } catch (URISyntaxException e) {
                throw new RiakIORuntimeException(e);
            }
            httpMethod.setURI(newURI);
        }
    }
    HttpEntity entity;
    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);
            }
        }

        if (!streamResponse) {
            EntityUtils.consume(entity);
        }

        return new DefaultHttpResponse(bucket, key, status, headers, body, stream, response, httpMethod);
    } catch (IOException e) {
        httpMethod.abort();
        return toss(new RiakIORuntimeException(e));
    }
}

From source file:com.ibm.watson.developer_cloud.service.WatsonService.java

/**
 * Execute the Http request./*from   ww  w .  j  a  v  a 2s. c o m*/
 * 
 * @param request
 *            the http request
 * 
 * @return the http response
 */
protected HttpResponse execute(HttpRequestBase request) {

    setAuthentication(request);

    if (getEndPoint() == null)
        throw new IllegalArgumentException("service endpoint was not specified");

    if (!request.containsHeader(ACCEPT)) {
        request.addHeader(ACCEPT, getDefaultContentType());
    }

    // from /v1/foo/bar to https://host:port/api/v1/foo/bar
    if (!request.getURI().isAbsolute()) {
        request.setURI(buildRequestURI(request));
    }
    HttpResponse response;

    //HttpHost proxy=new HttpHost("10.100.1.124",3128);

    log.log(Level.FINEST, "Request to: " + request.getURI());
    try {
        response = getHttpClient().execute(request);
        //ConnRouteParams.setDefaultProxy(response.getParams(),proxy);
    } catch (ClientProtocolException e) {
        log.log(Level.SEVERE, "ClientProtocolException", e);
        throw new RuntimeException(e);
    } catch (IOException e) {
        log.log(Level.SEVERE, "IOException", e);
        throw new RuntimeException(e);
    }

    final int status = response.getStatusLine().getStatusCode();
    log.log(Level.FINEST, "Response HTTP Status: " + status);

    if (status >= 200 && status < 300)
        return response;

    // There was a Client Error 4xx or a Server Error 5xx
    // Get the error message and create the exception
    String error = getErrorMessage(response);
    log.log(Level.SEVERE, "HTTP Status: " + status + ", message: " + error);

    switch (status) {
    case HttpStatus.SC_BAD_REQUEST: // HTTP 400
        throw new BadRequestException(error != null ? error : "Bad Request");
    case HttpStatus.SC_UNAUTHORIZED: // HTTP 401
        throw new UnauthorizedException("Unauthorized: Access is denied due to invalid credentials");
    case HttpStatus.SC_FORBIDDEN: // HTTP 403
        throw new ForbiddenException(error != null ? error : "Forbidden: Service refuse the request");
    case HttpStatus.SC_NOT_FOUND: // HTTP 404
        throw new NotFoundException(error != null ? error : "Not found");
    case HttpStatus.SC_NOT_ACCEPTABLE: // HTTP 406
        throw new ForbiddenException(error != null ? error : "Forbidden: Service refuse the request");
    case HttpStatus.SC_REQUEST_TOO_LONG: // HTTP 413
        throw new RequestTooLargeException(error != null ? error
                : "Request too large: The request entity is larger than the server is able to process");
    case HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE: // HTTP 415
        throw new UnsupportedException(error != null ? error
                : "Unsupported MIME type: The request entity has a media type which the server or resource does not support");
    case 429: // HTTP 429
        throw new TooManyRequestsException(error != null ? error : "Too many requests");
    case HttpStatus.SC_INTERNAL_SERVER_ERROR: // HTTP 500
        throw new InternalServerErrorException(error != null ? error : "Internal Server Error");
    case HttpStatus.SC_SERVICE_UNAVAILABLE: // HTTP 503
        throw new ServiceUnavailableException(error != null ? error : "Service Unavailable");
    default: // other errors
        throw new ServiceResponseException(status, error);
    }
}

From source file:ch.ifocusit.livingdoc.plugin.publish.confluence.client.ConfluenceRestClient.java

<T> T sendRequest(HttpRequestBase httpRequest, Function<HttpResponse, T> responseHandler) {
    CloseableHttpResponse response = null;

    try {/*  ww w  . j av a 2s. co  m*/

        final String encodedCredentials = "Basic "
                + Base64.getEncoder().encodeToString((username + ":" + password).getBytes());
        httpRequest.addHeader("Accept", "application/json");
        httpRequest.addHeader("Authorization", encodedCredentials);

        response = this.httpClient.execute(httpRequest, httpContext());

        return responseHandler.apply(response);
    } catch (IOException e) {
        throw new RuntimeException("Request could not be sent" + httpRequest, e);
    } finally {
        try {
            if (response != null) {
                response.close();
            }
        } catch (IOException ignored) {
        }
    }
}