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.opencastproject.loadtest.engage.util.TrustedHttpClient.java

/**
 * {@inheritDoc}/*from  ww  w. jav  a  2s . c  o m*/
 * @see org.opencastproject.loadtest.engage.util.remotetest.util.security.api.TrustedHttpClient#execute(org.apache.http.client.methods.HttpUriRequest)
 */
public HttpResponse execute(HttpUriRequest httpUriRequest) {
    // Add the request header to elicit a digest auth response
    httpUriRequest.addHeader(REQUESTED_AUTH_HEADER, DIGEST_AUTH);

    if ("GET".equalsIgnoreCase(httpUriRequest.getMethod())
            || "HEAD".equalsIgnoreCase(httpUriRequest.getMethod())) {
        // Set the user/pass
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass);
        httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);

        // Run the request (the http client handles the multiple back-and-forth requests)
        try {
            return httpClient.execute(httpUriRequest);
        } catch (IOException e) {
            throw new TrustedHttpClientException(e);
        }
    }

    // HttpClient doesn't handle the request dynamics for other verbs (especially when sending a streamed multipart
    // request), so we need to handle the details of the digest auth back-and-forth manually
    HttpRequestBase digestRequest;
    try {
        digestRequest = (HttpRequestBase) httpUriRequest.getClass().newInstance();
    } catch (Exception e) {
        throw new IllegalStateException("Can not create a new " + httpUriRequest.getClass().getName());
    }
    digestRequest.setURI(httpUriRequest.getURI());
    digestRequest.addHeader(REQUESTED_AUTH_HEADER, DIGEST_AUTH);
    String[] realmAndNonce = getRealmAndNonce(digestRequest);

    if (realmAndNonce != null) {
        // Set the user/pass
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass);

        // Set up the digest authentication with the required values
        DigestScheme digestAuth = new DigestScheme();
        digestAuth.overrideParamter("realm", realmAndNonce[0]);
        digestAuth.overrideParamter("nonce", realmAndNonce[1]);

        // Add the authentication header
        try {
            httpUriRequest.addHeader(digestAuth.authenticate(creds, httpUriRequest));
        } catch (Exception e) {
            // close the http connection(s)
            httpClient.getConnectionManager().shutdown();
            throw new TrustedHttpClientException(e);
        }
    }
    try {
        return httpClient.execute(httpUriRequest);
    } catch (Exception e) {
        // close the http connection(s)
        httpClient.getConnectionManager().shutdown();
        throw new TrustedHttpClientException(e);
    }
}

From source file:gmusic.api.api.comm.ApacheConnector.java

private HttpRequestBase adjustAddress(URI address, final HttpRequestBase request)
        throws MalformedURLException, URISyntaxException {
    if (address.toString().startsWith(HTTPS_PLAY_GOOGLE_COM_MUSIC_SERVICES)) {
        address = new URI(
                address.toURL() + String.format(COOKIE_FORMAT, getCookieValue("xt")) + "&format=jsarray");
    }/*from w w w.j a v a 2  s . com*/

    request.setURI(address);

    if (authorizationToken != null) {
        request.addHeader(GOOGLE_LOGIN_AUTH_KEY, String.format(GOOGLE_LOGIN_AUTH_VALUE, authorizationToken));
    }
    // if((address.toString().startsWith("https://android.clients.google.com/music/mplay"))
    // && deviceId != null)
    // {
    // request.addHeader("X-Device-ID", deviceId);
    // }

    return request;
}

From source file:org.nextlets.erc.utils.ERCUtils.java

public static String buildUrlAndParameters(ERCConfiguration configuration, String urlTemplate,
        HttpRequestBase req, String contentType, Map<String, String> params)
        throws UnsupportedEncodingException {

    if (urlTemplate == null || params == null) {
        return null;
    }//from   w  w  w  .  j av  a2  s  . c  o m

    String resUrl = ERCUtils.makeUrl(configuration.getServiceUrl(), urlTemplate);

    for (Iterator<Map.Entry<String, String>> it = params.entrySet().iterator(); it.hasNext();) {
        Map.Entry<String, String> entry = it.next();
        String key = '{' + entry.getKey() + '}';
        if (resUrl.contains(key)) {
            resUrl = resUrl.replace(key,
                    URLEncoder.encode(entry.getValue().toString(), configuration.getCharset()));
            it.remove();
        }
    }

    if (!params.isEmpty()) {
        if (req instanceof HttpEntityEnclosingRequest) {
            // PUT, POST
            HttpEntityEnclosingRequest eeReq = (HttpEntityEnclosingRequest) req;
            List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
            if (params.entrySet().size() == 1
                    && params.entrySet().iterator().next().getKey().equals(ERCParam.REQUEST_BODY)) {
                eeReq.setEntity(new StringEntity(params.entrySet().iterator().next().getValue()));
                req.addHeader(ERCConstants.HDR_CONTENT_TYPE, contentType);
            } else {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    urlParameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
                eeReq.setEntity(new UrlEncodedFormEntity(urlParameters,
                        Charset.forName(configuration.getCharset()).name()));
            }
        } else {
            // GET, DELETE
            boolean first = !resUrl.contains("?");
            StringBuilder sb = new StringBuilder(resUrl);
            for (Map.Entry<String, String> entry : params.entrySet()) {
                if (first) {
                    first = false;
                    sb.append('?');
                } else {
                    sb.append('&');
                }
                sb.append(entry.getKey()).append('=').append(URLEncoder.encode(entry.getValue(),
                        Charset.forName(configuration.getCharset()).name()));
            }
            resUrl = sb.toString();
        }
    }

    return resUrl;
}

From source file:org.talend.dataprep.command.GenericCommand.java

/**
 * Runs a data prep command with the following steps:
 * <ul>// ww  w  .j  a  v  a2 s  .  co  m
 * <li>Gets the HTTP command to execute (see {@link #execute(Supplier)}.</li>
 * <li>Gets the behavior to adopt based on returned HTTP code (see {@link #on(HttpStatus...)}).</li>
 * <li>If no behavior was defined for returned code, returns an error as defined in {@link #onError(Function)}</li>
 * <li>If a behavior was defined, invokes defined behavior.</li>
 * </ul>
 *
 * @return A instance of <code>T</code>.
 * @throws Exception If command execution fails.
 */
@Override
protected T run() throws Exception {
    final HttpRequestBase request = httpCall.get();

    // update request header with security token
    if (StringUtils.isNotBlank(authenticationToken)) {
        request.addHeader(AUTHORIZATION, authenticationToken);
    }

    final HttpResponse response;
    try {
        LOGGER.trace("Requesting {} {}", request.getMethod(), request.getURI());
        response = client.execute(request);
    } catch (Exception e) {
        throw onError.apply(e);
    }
    commandResponseHeaders = response.getAllHeaders();

    status = HttpStatus.valueOf(response.getStatusLine().getStatusCode());

    // do we have a behavior for this status code (even an error) ?
    // if yes use it
    BiFunction<HttpRequestBase, HttpResponse, T> function = behavior.get(status);
    if (function != null) {
        try {
            return function.apply(request, response);
        } catch (Exception e) {
            throw onError.apply(e);
        }
    }

    // handle response's HTTP status
    if (status.is4xxClientError() || status.is5xxServerError()) {
        // Http status >= 400 so apply onError behavior
        return callOnError(onError).apply(request, response);
    } else {
        // Http status is not error so apply onError behavior
        return behavior.getOrDefault(status, missingBehavior()).apply(request, response);
    }
}

From source file:com.appjma.appdeployer.service.Downloader.java

private void setupDefaultHeaders(HttpRequestBase request, String token) {
    HTTPUtils.setupDefaultHeaders(request);
    request.setHeader("Accept", "application/json");
    if (token != null) {
        request.addHeader("Authorization", "Bearer " + token);
    }// w ww  .  ja  v  a2  s  .c  o m
}

From source file:org.sentilo.common.rest.impl.RESTClientImpl.java

private void addSignedHeader(final HttpRequestBase httpRequest, final String body)
        throws GeneralSecurityException {
    final String currentDate = DateUtils.timestampToString(System.currentTimeMillis());
    final String hmac = HMACBuilder.buildHeader(body, host, secretKey, currentDate);
    httpRequest.addHeader(SentiloConstants.HMAC_HEADER, hmac);
    httpRequest.addHeader(SentiloConstants.DATE_HEADER, currentDate);
    logger.debug("Add header {} with value {}", SentiloConstants.HMAC_HEADER, hmac);
    logger.debug("Add header {} with value {}", SentiloConstants.DATE_HEADER, currentDate);
}

From source file:com.aliyun.oss.common.comm.DefaultServiceClient.java

private void setProxyAuthorizationIfNeed(HttpRequestBase httpRequest) {
    if (this.credentialsProvider != null) {
        String auth = this.config.getProxyUsername() + ":" + this.config.getProxyPassword();
        byte[] encodedAuth = Base64.encodeBase64(auth.getBytes());
        String authHeader = "Basic " + new String(encodedAuth);
        httpRequest.addHeader(AUTH.PROXY_AUTH_RESP, authHeader);
    }//from   ww  w.  ja  va  2s  .  com
}