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

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

Introduction

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

Prototype

Header getFirstHeader(String str);

Source Link

Usage

From source file:com.seleritycorp.common.base.http.client.HttpRequestTest.java

@Test
public void testSetUserAgentOverwrite() throws Exception {
    replayAll();//from  w w w  . j  a  va  2 s .  c o m

    HttpRequest request = createHttpRequest("foo");
    HttpRequest requestAfterSetting1 = request.setUserAgent("foo1");
    HttpRequest requestAfterSetting2 = request.setUserAgent("foo2");
    HttpResponse response = request.execute();

    verifyAll();

    assertThat(request).isSameAs(requestAfterSetting1);
    assertThat(request).isSameAs(requestAfterSetting2);
    assertThat(response).isEqualTo(httpResponse);

    HttpUriRequest backendRequest = backendRequestCapture.getValue();
    assertThat(backendRequest.getMethod()).isEqualTo("GET");
    assertThat(backendRequest.getURI().toString()).isEqualTo("foo");
    assertThat(backendRequest.getHeaders("User-Agent")).hasSize(1);
    assertThat(backendRequest.getFirstHeader("User-Agent").getValue()).isEqualTo("foo2");
}

From source file:com.cloud.utils.rest.HttpUriRequestBuilderTest.java

@Test
public void testBuildRequestWithJsonPayload() throws Exception {
    final HttpUriRequest request = HttpUriRequestBuilder.create().method(HttpMethods.GET).path("/path")
            .jsonPayload(Optional.of("{'key1':'value1'}")).build();

    assertThat(request, notNullValue());
    assertThat(request.getURI().getPath(), equalTo("/path"));
    assertThat(request.getURI().getScheme(), nullValue());
    assertThat(request.getURI().getQuery(), nullValue());
    assertThat(request.getURI().getHost(), nullValue());
    assertThat(request.getMethod(), equalTo(HttpGet.METHOD_NAME));
    assertThat(request.containsHeader(HttpConstants.CONTENT_TYPE), equalTo(true));
    assertThat(request.getFirstHeader(HttpConstants.CONTENT_TYPE).getValue(),
            equalTo(HttpConstants.JSON_CONTENT_TYPE));
    assertThat(request, HttpUriRequestPayloadMatcher.hasPayload("{'key1':'value1'}"));
}

From source file:com.createtank.payments.coinbase.RequestClient.java

private static JsonObject call(CoinbaseApi api, String method, RequestVerb verb, Map<String, String> params,
        boolean retry, String accessToken) throws IOException {
    if (api.allowSecure()) {

        HttpClient client = HttpClientBuilder.create().build();
        String url = BASE_URL + method;
        HttpUriRequest request = null;

        if (verb == RequestVerb.POST || verb == RequestVerb.PUT) {
            switch (verb) {
            case POST:
                request = new HttpPost(url);
                break;
            case PUT:
                request = new HttpPut(url);
                break;
            default:
                throw new RuntimeException("RequestVerb not implemented: " + verb);
            }//from  w ww. ja  v  a  2  s  . c om

            List<BasicNameValuePair> paramsBody = new ArrayList<BasicNameValuePair>();

            if (params != null) {
                List<BasicNameValuePair> convertedParams = convertParams(params);
                paramsBody.addAll(convertedParams);
            }

            ((HttpEntityEnclosingRequestBase) request).setEntity(new UrlEncodedFormEntity(paramsBody, "UTF-8"));
        } else {
            if (params != null) {
                url = url + "?" + createRequestParams(params);
            }

            if (verb == RequestVerb.GET) {
                request = new HttpGet(url);
            } else if (verb == RequestVerb.DELETE) {
                request = new HttpDelete(url);
            }
        }
        if (request == null)
            return null;

        if (accessToken != null)
            request.addHeader("Authorization", String.format("Bearer %s", accessToken));
        System.out.println("auth header: " + request.getFirstHeader("Authorization"));
        HttpResponse response = client.execute(request);
        int code = response.getStatusLine().getStatusCode();

        if (code == 401) {
            if (retry) {
                api.refreshAccessToken();
                call(api, method, verb, params, false, api.getAccessToken());
            } else {
                throw new IOException("Account is no longer valid");
            }
        } else if (code != 200) {
            throw new IOException("HTTP response " + code + " to request " + method);
        }

        String responseString = EntityUtils.toString(response.getEntity());
        if (responseString.startsWith("[")) {
            // Is an array
            responseString = "{response:" + responseString + "}";
        }

        JsonParser parser = new JsonParser();
        JsonObject resp = (JsonObject) parser.parse(responseString);
        System.out.println(resp.toString());
        return resp;
    }

    String paramStr = createRequestParams(params);
    String url = BASE_URL + method;

    if (paramStr != null && verb == RequestVerb.GET || verb == RequestVerb.DELETE)
        url += "?" + paramStr;

    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestMethod(verb.name());

    if (accessToken != null)
        conn.setRequestProperty("Authorization", String.format("Bearer %s", accessToken));

    if (verb != RequestVerb.GET && verb != RequestVerb.DELETE && paramStr != null) {
        conn.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
        writer.write(paramStr);
        writer.flush();
        writer.close();
    }

    int code = conn.getResponseCode();
    if (code == 401) {

        if (retry) {
            api.refreshAccessToken();
            return call(api, method, verb, params, false, api.getAccessToken());
        } else {
            throw new IOException("Account is no longer valid");
        }

    } else if (code != 200) {
        throw new IOException("HTTP response " + code + " to request " + method);
    }

    String responseString = getResponseBody(conn.getInputStream());
    if (responseString.startsWith("[")) {
        responseString = "{response:" + responseString + "}";
    }

    JsonParser parser = new JsonParser();
    return (JsonObject) parser.parse(responseString);
}

From source file:org.apache.camel.component.olingo2.api.impl.Olingo2AppImpl.java

/**
 * public for unit test, not to be used otherwise
 *///from   www.j av  a 2 s .c  om
public void execute(HttpUriRequest httpUriRequest, ContentType contentType,
        FutureCallback<HttpResponse> callback) {

    // add accept header when its not a form or multipart
    final String contentTypeString = contentType.toString();
    if (!ContentType.APPLICATION_FORM_URLENCODED.getMimeType().equals(contentType.getMimeType())
            && !contentType.getMimeType().startsWith(MULTIPART_MIME_TYPE)) {
        // otherwise accept what is being sent
        httpUriRequest.addHeader(HttpHeaders.ACCEPT, contentTypeString);
    }
    // is something being sent?
    if (httpUriRequest instanceof HttpEntityEnclosingRequestBase
            && httpUriRequest.getFirstHeader(HttpHeaders.CONTENT_TYPE) == null) {
        httpUriRequest.addHeader(HttpHeaders.CONTENT_TYPE, contentTypeString);
    }

    // set user specified custom headers
    if (httpHeaders != null && !httpHeaders.isEmpty()) {
        for (Map.Entry<String, String> entry : httpHeaders.entrySet()) {
            httpUriRequest.setHeader(entry.getKey(), entry.getValue());
        }
    }

    // add client protocol version if not specified
    if (!httpUriRequest.containsHeader(ODataHttpHeaders.DATASERVICEVERSION)) {
        httpUriRequest.addHeader(ODataHttpHeaders.DATASERVICEVERSION, ODataServiceVersion.V20);
    }
    if (!httpUriRequest.containsHeader(MAX_DATA_SERVICE_VERSION)) {
        httpUriRequest.addHeader(MAX_DATA_SERVICE_VERSION, ODataServiceVersion.V30);
    }

    // execute request
    client.execute(httpUriRequest, callback);
}

From source file:org.jets3t.service.impl.rest.httpclient.RestStorageService.java

/**
 * Creates an {@link org.apache.http.HttpRequest} object to handle a particular connection method.
 *
 * @param method/*ww  w  .jav a 2 s  . c om*/
 *        the HTTP method/connection-type to use, must be one of: PUT, HEAD, GET, DELETE
 * @param bucketName
 *        the bucket's name
 * @param objectKey
 *        the object's key name, may be null if the operation is on a bucket only.
 * @return
 *        the HTTP method object used to perform the request
 *
 * @throws org.jets3t.service.ServiceException
 */
protected HttpUriRequest setupConnection(HTTP_METHOD method, String bucketName, String objectKey,
        Map<String, String> requestParameters) throws ServiceException {
    if (bucketName == null) {
        throw new ServiceException("Cannot connect to S3 Service with a null path");
    }

    boolean disableDnsBuckets = this.getDisableDnsBuckets();
    String endPoint = this.getEndpoint();
    String hostname = ServiceUtils.generateS3HostnameForBucket(bucketName, disableDnsBuckets, endPoint);

    // Allow for non-standard virtual directory paths on the server-side
    String virtualPath = this.getVirtualPath();

    // Determine the resource string (ie the item's path in S3, including the bucket name)
    String resourceString = "/";
    if (hostname.equals(endPoint) && bucketName.length() > 0) {
        resourceString += bucketName;
    }
    if (objectKey != null) {
        resourceString += "/" + RestUtils.encodeUrlString(objectKey);
    }
    //        resourceString += (objectKey != null ? RestUtils.encodeUrlString(objectKey) : "");

    // Construct a URL representing a connection for the S3 resource.
    String url = null;
    if (isHttpsOnly()) {
        int securePort = this.getHttpsPort();
        url = "https://" + hostname + ":" + securePort + virtualPath + resourceString;
    } else {
        int insecurePort = this.getHttpPort();
        url = "http://" + hostname + ":" + insecurePort + virtualPath + resourceString;
    }
    if (log.isDebugEnabled()) {
        log.debug("S3 URL: " + url);
    }

    // Add additional request parameters to the URL for special cases (eg ACL operations)
    url = addRequestParametersToUrlPath(url, requestParameters);

    HttpUriRequest httpMethod = null;
    if (HTTP_METHOD.PUT.equals(method)) {
        httpMethod = new HttpPut(url);
    } else if (HTTP_METHOD.POST.equals(method)) {
        httpMethod = new HttpPost(url);
    } else if (HTTP_METHOD.HEAD.equals(method)) {
        httpMethod = new HttpHead(url);
    } else if (HTTP_METHOD.GET.equals(method)) {
        httpMethod = new HttpGet(url);
    } else if (HTTP_METHOD.DELETE.equals(method)) {
        httpMethod = new HttpDelete(url);
    } else {
        throw new IllegalArgumentException("Unrecognised HTTP method name: " + method);
    }

    // Set mandatory Request headers.
    if (httpMethod.getFirstHeader("Date") == null) {
        httpMethod.setHeader("Date", ServiceUtils.formatRfc822Date(getCurrentTimeWithOffset()));
    }

    return httpMethod;
}

From source file:org.jets3t.service.impl.rest.httpclient.RestStorageService.java

/**
 * Performs an HTTP PUT request using the {@link #performRequest} method.
 *
 * @param bucketName//from  ww w .j  ava 2s.  com
 *        the name of the bucket the object will be stored in.
 * @param objectKey
 *        the key (name) of the object to be stored.
 * @param metadata
 *        map of name/value pairs to add as metadata to any S3 objects created.
 * @param requestParameters
 *        parameters to add to the request URL as GET params
 * @param requestEntity
 *        an HttpClient object that encapsulates the object and data contents that will be
 *        uploaded. This object supports the resending of object data, when possible.
 * @param autoRelease
 *        if true, the HTTP Method object will be released after the request has
 *        completed and the connection will be closed. If false, the object will
 *        not be released and the caller must take responsibility for doing this.
 * @return
 *        a package including the HTTP method object used to perform the request, and the
 *        content length (in bytes) of the object that was PUT to S3.
 *
 * @throws org.jets3t.service.ServiceException
 */
protected HttpResponseAndByteCount performRestPut(String bucketName, String objectKey,
        Map<String, Object> metadata, Map<String, String> requestParameters, HttpEntity requestEntity,
        boolean autoRelease) throws ServiceException {
    // Add any request parameters.
    HttpUriRequest httpMethod = setupConnection(HTTP_METHOD.PUT, bucketName, objectKey, requestParameters);

    Map<String, Object> renamedMetadata = renameMetadataKeys(metadata);
    addMetadataToHeaders(httpMethod, renamedMetadata);

    long contentLength = 0;

    if (log.isTraceEnabled()) {
        log.trace("Put request with entity: " + requestEntity);
    }
    if (requestEntity != null) {
        ((HttpPut) httpMethod).setEntity(requestEntity);

        /* Explicitly apply any latent Content-Type header from the request entity to the
         * httpMethod to ensure it is included in the request signature, since it will be
         * included in the wire request by HttpClient. But only apply the latent mimetype
         * if an explicit Content-Type is not already set. See issue #109
         */
        if (requestEntity.getContentType() != null && httpMethod.getFirstHeader("Content-Type") == null) {
            httpMethod.setHeader(requestEntity.getContentType());
        }
    }

    HttpResponse result = performRequest(httpMethod, new int[] { 200, 204 });

    if (requestEntity != null) {
        // Respond with the actual guaranteed content length of the uploaded data.
        contentLength = ((HttpPut) httpMethod).getEntity().getContentLength();
    }

    if (autoRelease) {
        releaseConnection(result);
    }

    return new HttpResponseAndByteCount(result, contentLength);
}