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

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

Introduction

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

Prototype

URI getURI();

Source Link

Document

Returns the URI this request uses, such as <code>http://example.org/path/to/file</code>.

Usage

From source file:ch.entwine.weblounge.test.util.TestSiteUtils.java

/**
 * Test for the correct response when modified since header is set.
 * // w ww  .  ja v  a 2 s .  com
 * @param request
 *          the http request
 * @param date
 *          the expected modification date
 * @param logger
 *          used to log test output
 * @param params
 *          the request parameters
 * @throws Exception
 *           if processing the request fails
 */
public static void testModifiedHeader(HttpUriRequest request, Date modificationDate, Logger logger,
        String[][] params) throws Exception {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    Date before = new Date(modificationDate.getTime() - Times.MS_PER_DAY);
    Date after = new Date(modificationDate.getTime() + Times.MS_PER_DAY);
    SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
    try {
        request.removeHeaders("If-None-Match");
        request.setHeader("If-Modified-Since", format.format(after));
        logger.info("Sending 'If-Modified-Since' request to {}", request.getURI());
        HttpResponse response = TestUtils.request(httpClient, request, params);
        assertEquals(HttpServletResponse.SC_NOT_MODIFIED, response.getStatusLine().getStatusCode());
        assertNull(response.getEntity());
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

    httpClient = new DefaultHttpClient();
    try {
        request.removeHeaders("If-None-Match");
        request.setHeader("If-Modified-Since", format.format(before));
        logger.info("Sending 'If-Modified-Since' request to {}", request.getURI());
        HttpResponse response = TestUtils.request(httpClient, request, params);
        assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        assertNotNull(response.getEntity());
        response.getEntity().consumeContent();
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:org.apache.taverna.activities.rest.HTTPRequestHandler.java

/**
 * TODO - REDIRECTION output:: if there was no redirection, should just show
 * the actual initial URL?// w w w . ja v a2 s  .c o  m
 *
 * @param httpRequest
 * @param acceptHeaderValue
 */
private static HTTPRequestResponse performHTTPRequest(ClientConnectionManager connectionManager,
        HttpRequestBase httpRequest, RESTActivityConfigurationBean configBean,
        Map<String, String> urlParameters, CredentialsProvider credentialsProvider) {
    // headers are set identically for all HTTP methods, therefore can do
    // centrally - here

    // If the user wants to set MIME type for the 'Accepts' header
    String acceptsHeaderValue = configBean.getAcceptsHeaderValue();
    if ((acceptsHeaderValue != null) && !acceptsHeaderValue.isEmpty()) {
        httpRequest.setHeader(ACCEPT_HEADER_NAME, URISignatureHandler.generateCompleteURI(acceptsHeaderValue,
                urlParameters, configBean.getEscapeParameters()));
    }

    // See if user wanted to set any other HTTP headers
    ArrayList<ArrayList<String>> otherHTTPHeaders = configBean.getOtherHTTPHeaders();
    if (!otherHTTPHeaders.isEmpty())
        for (ArrayList<String> httpHeaderNameValuePair : otherHTTPHeaders)
            if (httpHeaderNameValuePair.get(0) != null && !httpHeaderNameValuePair.get(0).isEmpty()) {
                String headerParameterizedValue = httpHeaderNameValuePair.get(1);
                String headerValue = URISignatureHandler.generateCompleteURI(headerParameterizedValue,
                        urlParameters, configBean.getEscapeParameters());
                httpRequest.setHeader(httpHeaderNameValuePair.get(0), headerValue);
            }

    try {
        HTTPRequestResponse requestResponse = new HTTPRequestResponse();
        DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, null);
        ((DefaultHttpClient) httpClient).setCredentialsProvider(credentialsProvider);
        HttpContext localContext = new BasicHttpContext();

        // Set the proxy settings, if any
        if (System.getProperty(PROXY_HOST) != null && !System.getProperty(PROXY_HOST).isEmpty()) {
            // Instruct HttpClient to use the standard
            // JRE proxy selector to obtain proxy information
            ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
                    httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
            httpClient.setRoutePlanner(routePlanner);
            // Do we need to authenticate the user to the proxy?
            if (System.getProperty(PROXY_USERNAME) != null && !System.getProperty(PROXY_USERNAME).isEmpty())
                // Add the proxy username and password to the list of
                // credentials
                httpClient.getCredentialsProvider().setCredentials(
                        new AuthScope(System.getProperty(PROXY_HOST),
                                Integer.parseInt(System.getProperty(PROXY_PORT))),
                        new UsernamePasswordCredentials(System.getProperty(PROXY_USERNAME),
                                System.getProperty(PROXY_PASSWORD)));
        }

        // execute the request
        HttpResponse response = httpClient.execute(httpRequest, localContext);

        // record response code
        requestResponse.setStatusCode(response.getStatusLine().getStatusCode());
        requestResponse.setReasonPhrase(response.getStatusLine().getReasonPhrase());

        // record header values for Content-Type of the response
        requestResponse.setResponseContentTypes(response.getHeaders(CONTENT_TYPE_HEADER_NAME));

        // track where did the final redirect go to (if there was any)
        HttpHost targetHost = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        HttpUriRequest targetRequest = (HttpUriRequest) localContext
                .getAttribute(ExecutionContext.HTTP_REQUEST);
        requestResponse.setRedirectionURL("" + targetHost + targetRequest.getURI());
        requestResponse.setRedirectionHTTPMethod(targetRequest.getMethod());
        requestResponse.setHeaders(response.getAllHeaders());

        /* read and store response body
         (check there is some content - negative length of content means
         unknown length;
         zero definitely means no content...)*/
        // TODO - make sure that this test is sufficient to determine if
        // there is no response entity
        if (response.getEntity() != null && response.getEntity().getContentLength() != 0)
            requestResponse.setResponseBody(readResponseBody(response.getEntity()));

        // release resources (e.g. connection pool, etc)
        httpClient.getConnectionManager().shutdown();
        return requestResponse;
    } catch (Exception ex) {
        return new HTTPRequestResponse(ex);
    }
}

From source file:org.jets3t.service.utils.SignatureUtils.java

/**
 * Calculate AWS Version 4 signature for a HTTP request and apply the
 * appropriate "Authorization" header value to authorize it.
 *
 * @param httpMethod/*from w  ww  . j a  v  a 2 s .c o  m*/
 * the request's HTTP method just prior to sending
 * @param requestSignatureVersion
 * request signature version string, e.g. "AWS4-HMAC-SHA256"
 * @param providerCredentials
 * account holder's access and secret key credentials
 * @param requestPayloadHexSha256Hash
 * hex-encoded SHA256 hash of request's payload.
 * @param region
 * region to which the request will be sent
 * {@link "http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region"}
 */
public static void awsV4SignRequestAuthorizationHeader(String requestSignatureVersion,
        HttpUriRequest httpMethod, ProviderCredentials providerCredentials, String requestPayloadHexSha256Hash,
        String region) {
    // Ensure the required Host header is set prior to signing.
    if (httpMethod.getFirstHeader("Host") == null) {
        httpMethod.setHeader("Host", httpMethod.getURI().getHost());
    }

    // Generate AWS-flavoured ISO8601 timestamp string
    String timestampISO8601 = SignatureUtils.awsV4ParseAndFormatDate(httpMethod);

    // Apply AWS-flavoured ISO8601 timestamp string to "x-aws-date"
    // metadata, otherwise if only the Date header is present and it is
    // RFC 822 formatted S3 expects that date to be part of the string
    // to sign, not the AWS-flavoured ISO8601 timestamp as claimed by the
    // documentation.
    // TODO This shouldn't be necessary, confirm it really is...
    if (httpMethod.getFirstHeader("x-amz-date") == null) {
        httpMethod.setHeader("x-amz-date", timestampISO8601);
    }

    // Canonical request string
    String canonicalRequestString = SignatureUtils.awsV4BuildCanonicalRequestString(httpMethod,
            requestPayloadHexSha256Hash);

    // String to sign
    String stringToSign = SignatureUtils.awsV4BuildStringToSign(requestSignatureVersion, canonicalRequestString,
            timestampISO8601, region);

    // Signing key
    byte[] signingKey = SignatureUtils.awsV4BuildSigningKey(providerCredentials.getSecretKey(),
            timestampISO8601, region);

    // Request signature
    String signature = ServiceUtils
            .toHex(ServiceUtils.hmacSHA256(signingKey, ServiceUtils.stringToBytes(stringToSign)));

    // Authorization header value
    String authorizationHeaderValue = SignatureUtils.awsV4BuildAuthorizationHeaderValue(
            providerCredentials.getAccessKey(), signature, requestSignatureVersion, canonicalRequestString,
            timestampISO8601, region);

    httpMethod.setHeader("Authorization", authorizationHeaderValue);
}

From source file:com.cooliris.media.UriTexture.java

private static final BufferedInputStream createInputStreamFromRemoteUrl(String uri,
        ClientConnectionManager connectionManager) {
    InputStream contentInput = null;
    if (connectionManager == null) {
        try {//from   ww w .j a v  a 2 s  . c  o  m
            URL url = new URI(uri).toURL();
            URLConnection conn = url.openConnection();
            conn.connect();
            contentInput = conn.getInputStream();
        } catch (Exception e) {
            Log.w(TAG, "Request failed: " + uri);
            e.printStackTrace();
            return null;
        }
    } else {
        // We create a cancelable http request from the client
        final DefaultHttpClient mHttpClient = new DefaultHttpClient(connectionManager, HTTP_PARAMS);
        HttpUriRequest request = new HttpGet(uri);
        // Execute the HTTP request.
        HttpResponse httpResponse = null;
        try {
            httpResponse = mHttpClient.execute(request);
            HttpEntity entity = httpResponse.getEntity();
            if (entity != null) {
                // Wrap the entity input stream in a GZIP decoder if
                // necessary.
                contentInput = entity.getContent();
            }
        } catch (Exception e) {
            Log.w(TAG, "Request failed: " + request.getURI());
            return null;
        }
    }
    if (contentInput != null) {
        return new BufferedInputStream(contentInput, 4096);
    } else {
        return null;
    }
}

From source file:com.ocp.media.UriTexture.java

private static final BufferedInputStream createInputStreamFromRemoteUrl(String uri,
        ClientConnectionManager connectionManager) {
    InputStream contentInput = null;
    if (connectionManager == null) {
        try {//from www . j  ava 2s  .  co m
            URL url = new URI(uri).toURL();
            URLConnection conn = url.openConnection();
            conn.connect();
            contentInput = conn.getInputStream();
        } catch (Exception e) {
            Log.w(Gallery.TAG, TAG + ": " + "Request failed: " + uri);
            e.printStackTrace();
            return null;
        }
    } else {
        // We create a cancelable http request from the client
        final DefaultHttpClient mHttpClient = new DefaultHttpClient(connectionManager, HTTP_PARAMS);
        HttpUriRequest request = new HttpGet(uri);
        // Execute the HTTP request.
        HttpResponse httpResponse = null;
        try {
            httpResponse = mHttpClient.execute(request);
            HttpEntity entity = httpResponse.getEntity();
            if (entity != null) {
                // Wrap the entity input stream in a GZIP decoder if
                // necessary.
                contentInput = entity.getContent();
            }
        } catch (Exception e) {
            Log.w(Gallery.TAG, TAG + ": " + "Request failed: " + request.getURI());
            return null;
        }
    }
    if (contentInput != null) {
        return new BufferedInputStream(contentInput, 4096);
    } else {
        return null;
    }
}

From source file:com.novoda.commons.net.httpclient.NovodaHttpClient.java

/**
 * Generates a cURL command equivalent to the given request.
 *//*from w  w  w  . j ava2 s. co  m*/
private static String toCurl(HttpUriRequest request, boolean logAuthToken) throws IOException {
    StringBuilder builder = new StringBuilder();

    builder.append("curl ");

    for (Header header : request.getAllHeaders()) {
        if (!logAuthToken && (header.getName().equals("Authorization") || header.getName().equals("Cookie"))) {
            continue;
        }
        builder.append("--header \"");
        builder.append(header.toString().trim());
        builder.append("\" ");
    }

    URI uri = request.getURI();

    // If this is a wrapped request, use the URI from the original
    // request instead. getURI() on the wrapper seems to return a
    // relative URI. We want an absolute URI.
    if (request instanceof RequestWrapper) {
        HttpRequest original = ((RequestWrapper) request).getOriginal();
        if (original instanceof HttpUriRequest) {
            uri = ((HttpUriRequest) original).getURI();
        }
    }

    builder.append("\"");
    builder.append(uri);
    builder.append("\"");

    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request;
        HttpEntity entity = entityRequest.getEntity();
        if (entity != null && entity.isRepeatable()) {
            if (entity.getContentLength() < 1024) {
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                entity.writeTo(stream);
                String entityString = stream.toString();

                builder.append(" --data-ascii \"").append(entityString).append("\"");
            } else {
                builder.append(" [TOO MUCH DATA TO INCLUDE]");
            }
        }
    }

    return builder.toString();
}

From source file:br.com.anteros.android.synchronism.communication.AndroidHttpClient.java

/**
 * Generates a cURL command equivalent to the given request.
 *//*from w  ww . ja  v a  2 s  .  c om*/
private static String toCurl(HttpUriRequest request, boolean logAuthToken) throws IOException {
    StringBuilder builder = new StringBuilder();

    builder.append("curl ");

    for (Header header : request.getAllHeaders()) {
        if (!logAuthToken && (header.getName().equals("Authorization") || header.getName().equals("Cookie"))) {
            continue;
        }
        builder.append("--header \"");
        builder.append(header.toString().trim());
        builder.append("\" ");
    }

    URI uri = request.getURI();

    // If this is a wrapped request, use the URI from the original
    // request instead. getURI() on the wrapper seems to return a
    // relative URI. We want an absolute URI.
    if (request instanceof RequestWrapper) {
        HttpRequest original = ((RequestWrapper) request).getOriginal();
        if (original instanceof HttpUriRequest) {
            uri = ((HttpUriRequest) original).getURI();
        }
    }

    builder.append("\"");
    builder.append(uri);
    builder.append("\"");

    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request;
        HttpEntity entity = entityRequest.getEntity();
        if (entity != null && entity.isRepeatable()) {
            if (entity.getContentLength() < 1024) {
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                entity.writeTo(stream);
                String entityString = stream.toString();

                // TODO: Check the content type, too.
                builder.append(" --data-ascii \"").append(entityString).append("\"");
            } else {
                builder.append(" [TOO MUCH DATA TO INCLUDE]");
            }
        }
    }

    return builder.toString();
}

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

@Override
protected String featureValueOf(final HttpUriRequest actual) {
    return actual.getURI().getPath();
}

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

@Override
protected String featureValueOf(final HttpUriRequest actual) {
    return actual.getURI().getQuery();
}

From source file:org.apache.hadoop.gateway.hbase.HBaseCookieManager.java

protected HttpRequest createKerberosAuthenticationRequest(HttpUriRequest userRequest) {
    URI userUri = userRequest.getURI();
    try {//  w  w  w .j a  v  a2 s .c o  m
        URI authUri = new URI(userUri.getScheme(), null, userUri.getHost(), userUri.getPort(), "/version",
                userUri.getQuery(), null);
        HttpRequest authRequest = new HttpGet(authUri);
        return authRequest;
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException(userUri.toString(), e);
    }
}