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

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

Introduction

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

Prototype

String getMethod();

Source Link

Document

Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other.

Usage

From source file:com.mber.client.HTTParty.java

private static Call execute(final HttpUriRequest request) throws IOException {
    HttpClient client = new DefaultHttpClient();
    try {//from  w w  w .j a va  2 s . co m
        request.addHeader("REST-API-Version", MBER_VERSION);
        HttpResponse response = client.execute(request);
        String body = toString(response.getEntity().getContent());
        return new Call(request.getMethod(), request.getURI(), response.getStatusLine().getStatusCode(), body);
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:com.helger.httpclient.HttpDebugger.java

/**
 * Call after an invocation.//from   ww  w. j  a va  2 s  . co m
 *
 * @param aRequest
 *        The source request. May not be modified internally. May not be
 *        <code>null</code>.
 * @param aResponse
 *        The response object retrieved. May be anything including
 *        <code>null</code> (e.g. in case of exception).
 * @param aCaughtException
 *        The caught exception. May be <code>null</code>.
 * @since 8.8.2
 */
public static void afterRequest(@Nonnull final HttpUriRequest aRequest, @Nullable final Object aResponse,
        @Nullable final Throwable aCaughtException) {
    if (isEnabled())
        if (LOGGER.isInfoEnabled()) {
            final HttpResponseException aHex = aCaughtException instanceof HttpResponseException
                    ? (HttpResponseException) aCaughtException
                    : null;
            LOGGER.info(
                    "After HTTP call: " + aRequest.getMethod()
                            + (aResponse != null ? ". Response: " + aResponse : "")
                            + (aHex != null ? ". Status " + aHex.getStatusCode() : ""),
                    aHex != null ? null : aCaughtException);
        }
}

From source file:org.soyatec.windowsazure.internal.MessageCanonicalizer2.java

/**
 * Create a canonicalized string with the httpRequest and resourceUriComponents. 
 * //w  w  w.j  av a  2 s .c o m
 * @param request
 *          The HttpWebRequest object.
 * @param uriComponents
 *          Components of the Uri extracted out of the request.
 * @return A canonicalized string of the HTTP request.
 */
public static String canonicalizeHttpRequest(HttpRequest request, ResourceUriComponents uriComponents) {
    if (!(request instanceof HttpUriRequest)) {
        throw new IllegalArgumentException("Request should be a URI http request");
    }
    HttpUriRequest rq = (HttpUriRequest) request;
    HttpEntity body = null;
    if (rq instanceof HttpEntityEnclosingRequest) {
        body = ((HttpEntityEnclosingRequest) rq).getEntity();
    }
    return canonicalizeHttpRequest(rq.getURI(), uriComponents, rq.getMethod(),
            HttpUtilities.parseRequestContentType(rq), Utilities.emptyString(),
            HttpUtilities.parseHttpHeaders(rq), body);
}

From source file:org.fcrepo.integration.http.api.AbstractResourceIT.java

/**
 * Execute an HTTP request and close the response.
 *
 * @param req the request to execute/*ww  w  . j av  a 2  s .  c  o  m*/
 */
protected static void executeAndClose(final HttpUriRequest req) {
    logger.debug("Executing: " + req.getMethod() + " to " + req.getURI());
    try {
        execute(req).close();
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.fcrepo.integration.http.api.AbstractResourceIT.java

/**
 * Execute an HTTP request and return the open response.
 *
 * @param req Request to execute/*from w w w.  j  av  a2 s  . c  o m*/
 * @return the open response
 * @throws IOException in case of an IOException
 */
protected static CloseableHttpResponse execute(final HttpUriRequest req) throws IOException {
    logger.debug("Executing: " + req.getMethod() + " to " + req.getURI());
    return client.execute(req);
}

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

/**
 * Build the canonical request string for a REST/HTTP request to a storage
 * service for the AWS Request Signature version 4.
 *
 * {@link "http://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-header-based-auth.html"}
 *
 * @param httpMethod//from   www  . ja va 2 s.  c  om
 * the request's HTTP method just prior to sending
 * @param requestPayloadHexSha256Hash
 * hex-encoded SHA256 hash of request's payload.
 * May be null or "" in which case the default SHA256 hash of an empty string is used.
 * May also be "UNSIGNED-PAYLOAD" for generating pre-signed request signatures.
 * @return canonical request string according to AWS Request Signature version 4
 */
public static String awsV4BuildCanonicalRequestString(HttpUriRequest httpMethod,
        String requestPayloadHexSha256Hash) {
    URI uri = httpMethod.getURI();
    String httpRequestMethod = httpMethod.getMethod();

    Map<String, String> headersMap = new HashMap<String, String>();
    Header[] headers = httpMethod.getAllHeaders();
    for (Header header : headers) {
        // Trim whitespace and make lower-case for header names
        String name = header.getName().trim().toLowerCase();
        // Trim whitespace for header values
        String value = header.getValue().trim();
        headersMap.put(name, value);
    }

    return awsV4BuildCanonicalRequestString(uri, httpRequestMethod, headersMap, requestPayloadHexSha256Hash);
}

From source file:com.android.mms.service.http.NetworkAwareHttpClient.java

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

    builder.append("curl ");

    // add in the method
    builder.append("-X ");
    builder.append(request.getMethod());
    builder.append(" ");

    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);

                if (isBinaryContent(request)) {
                    String base64 = Base64.encodeToString(stream.toByteArray(), Base64.NO_WRAP);
                    builder.insert(0, "echo '" + base64 + "' | base64 -d > /tmp/$$.bin; ");
                    builder.append(" --data-binary @/tmp/$$.bin");
                } else {
                    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:org.apache.taverna.activities.rest.HTTPRequestHandler.java

/**
 * TODO - REDIRECTION output:: if there was no redirection, should just show
 * the actual initial URL?/* w ww. jav  a 2  s . co  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:com.cloud.utils.rest.HttpUriRequestMethodMatcher.java

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

From source file:org.fcrepo.indexer.integration.webapp.SanityCheckIT.java

protected int getStatus(final HttpUriRequest method) throws IOException {
    logger.info("Executing: " + method.getMethod() + " to " + method.getURI());
    return client.execute(method).getStatusLine().getStatusCode();
}