Example usage for org.apache.http.client.methods HttpUriRequest addHeader

List of usage examples for org.apache.http.client.methods HttpUriRequest addHeader

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpUriRequest addHeader.

Prototype

void addHeader(String str, String str2);

Source Link

Usage

From source file:org.opentravel.otm.forum2016.am.RESTClientOperation.java

/**
 * Invokes the HTTP request using the OAuth2 credentials established by the factory.
 * /*from   w  w w .  j a  va  2s.  c o  m*/
 * @param request  the request to be executed
 * @return R
 * @throws IOException  thrown if an error occurrs during execution of the request
 */
protected R execute(HttpUriRequest request) throws IOException {
    OAuth2AccessToken token = factory.getAccessToken(getSecurityScope());
    R responseObj = null;

    request.addHeader("Authorization", token.getTokenType() + " " + token.getAccessToken());

    try (CloseableHttpClient client = newHttpClient()) {
        HttpResponse response = client.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();

        if ((statusCode >= 200) && (statusCode <= 299)) {
            responseObj = unmarshallResponse(response);

        } else {
            throw new IOException("Service invocation error [" + statusCode + "]:" + readPayload(response));
        }
        return responseObj;
    }
}

From source file:org.apache.abdera2.common.protocol.RequestHelper.java

public static HttpUriRequest createRequest(String method, String uri, HttpEntity entity,
        RequestOptions options) {/*from   w ww .j ava  2 s . c om*/
    if (method == null)
        return null;
    if (options == null)
        options = createAtomDefaultRequestOptions().get();
    Method m = Method.get(method);
    Method actual = null;
    HttpUriRequest httpMethod = null;
    if (options.isUsePostOverride() && !nopostoveride.contains(m)) {
        actual = m;
        m = Method.POST;
    }
    if (m == GET)
        httpMethod = new HttpGet(uri);
    else if (m == POST) {
        httpMethod = new HttpPost(uri);
        if (entity != null)
            ((HttpPost) httpMethod).setEntity(entity);
    } else if (m == PUT) {
        httpMethod = new HttpPut(uri);
        if (entity != null)
            ((HttpPut) httpMethod).setEntity(entity);
    } else if (m == DELETE)
        httpMethod = new HttpDelete(uri);
    else if (m == HEAD)
        httpMethod = new HttpHead(uri);
    else if (m == OPTIONS)
        httpMethod = new HttpOptions(uri);
    else if (m == TRACE)
        httpMethod = new HttpTrace(uri);
    //        else if (m == PATCH)
    //          httpMethod = new ExtensionRequest(m.name(),uri,entity);
    else
        httpMethod = new ExtensionRequest(m.name(), uri, entity);
    if (actual != null) {
        httpMethod.addHeader("X-HTTP-Method-Override", actual.name());
    }
    initHeaders(options, httpMethod);
    HttpParams params = httpMethod.getParams();
    if (!options.isUseExpectContinue()) {
        params.setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
    } else {
        if (options.getWaitForContinue() > -1)
            params.setIntParameter(CoreProtocolPNames.WAIT_FOR_CONTINUE, options.getWaitForContinue());
    }
    if (!(httpMethod instanceof HttpEntityEnclosingRequest))
        params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, options.isFollowRedirects());
    return httpMethod;
}

From source file:com.vmware.photon.controller.client.RestClient.java

@VisibleForTesting
protected HttpUriRequest addAuthHeader(HttpUriRequest request) {
    if (sharedSecret != null) {
        request.addHeader(AUTHORIZATION_HEADER, AUTHORIZATION_METHOD + sharedSecret);
    }//from w  w  w.  ja  v  a  2s .co  m
    return request;
}

From source file:com.predic8.membrane.core.transport.ExceptionHandlingTest.java

private HttpUriRequest createRequest() throws UnsupportedEncodingException {
    String url = "http://localhost:" + getPort() + "/";
    HttpUriRequest get = null;
    switch (contentType) {
    case JSON://from  ww  w . ja  va2 s  .  c o  m
        get = new HttpGet(url);
        get.addHeader(Header.CONTENT_TYPE, MimeType.APPLICATION_JSON_UTF8);
        break;
    case XML:
        get = new HttpPost(url);
        get.addHeader(Header.CONTENT_TYPE, MimeType.TEXT_XML_UTF8);
        ((HttpPost) get).setEntity(new StringEntity("<foo />"));
        break;
    case SOAP:
        get = new HttpPost(url);
        get.addHeader(Header.CONTENT_TYPE, MimeType.TEXT_XML_UTF8);
        ((HttpPost) get).setEntity(new StringEntity(HttpUtil.getFaultSOAPBody("", "")));
        break;
    default:
        get = new HttpGet(url);
        break;
    }
    return get;
}

From source file:com.lurencun.cfuture09.androidkit.http.async.SyncHttpClient.java

@Override
protected void sendRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest,
        String contentType, AsyncHttpResponseHandler responseHandler, Context context) {
    if (contentType != null) {
        uriRequest.addHeader("Content-Type", contentType);
    }/*from w  ww.j  a v  a2  s  . c  o  m*/

    /*
     * will execute the request directly
     */
    new AsyncHttpRequest(client, httpContext, uriRequest, responseHandler).run();
}

From source file:org.matmaul.freeboxos.internal.RestManager.java

public InputStream execute(HttpUriRequest req, boolean retryAuth) throws FreeboxException {
    if (loginManager.getSessionToken() != null) {
        req.addHeader(getAuthHeader(), loginManager.getSessionToken());
    }/*  w w  w .  j av a 2 s  .  c  o  m*/
    HttpResponse res;
    try {
        res = httpClient.execute(req);
        return res.getEntity().getContent();
    } catch (Exception e) {
        throw new FreeboxException(e);
    }

}

From source file:org.dthume.spring.http.client.httpcomponents.HttpComponentsClientHttpRequest.java

private void addHeaders(final HttpUriRequest request, final HttpHeaders headers) {
    for (Map.Entry<String, List<String>> entry : headers.entrySet())
        for (final String value : entry.getValue())
            request.addHeader(entry.getKey(), value);
}

From source file:org.springframework.boot.cli.command.init.InitializrService.java

private CloseableHttpResponse execute(HttpUriRequest request, Object url, String description) {
    try {/*from   w ww . ja  v  a2 s.co m*/
        request.addHeader("User-Agent", "SpringBootCli/" + getClass().getPackage().getImplementationVersion());
        return getHttp().execute(request);
    } catch (IOException ex) {
        throw new ReportableException(
                "Failed to " + description + " from service at '" + url + "' (" + ex.getMessage() + ")");
    }
}

From source file:com.demo.wtm.service.RestService.java

private HttpUriRequest addBodyParams(HttpUriRequest request) throws Exception {
    if (jsonBody != null) {
        request.addHeader("Content-Type", "application/json");
        if (request instanceof HttpPost)
            ((HttpPost) request).setEntity(new StringEntity(jsonBody, "UTF-8"));
        else if (request instanceof HttpPut)
            ((HttpPut) request).setEntity(new StringEntity(jsonBody, "UTF-8"));

    } else if (!params.isEmpty()) {
        if (request instanceof HttpPost)
            ((HttpPost) request).setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
        else if (request instanceof HttpPut)
            ((HttpPut) request).setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
    }/*  w  w w. j av a2 s. c om*/
    return request;
}

From source file:org.opencastproject.loadtest.engage.util.TrustedHttpClient.java

/**
 * {@inheritDoc}/* w  ww .  j  av a 2 s  .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);
    }
}