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:com.predic8.membrane.core.transport.ExceptionHandlingTest.java

public static String getAndAssert(int expectedHttpStatusCode, HttpUriRequest request)
        throws ParseException, IOException {
    if (hc == null)
        hc = HttpClientBuilder.create().build();
    HttpResponse res = hc.execute(request);
    try {//from w  ww  .  ja  v a  2s  .c  o m
        assertEquals(expectedHttpStatusCode, res.getStatusLine().getStatusCode());
    } catch (AssertionError e) {
        throw new AssertionError(e.getMessage() + " while fetching " + request.getURI());
    }
    HttpEntity entity = res.getEntity();
    return entity == null ? "" : EntityUtils.toString(entity);
}

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

/**
 * Create a canonicalized string with the httpRequest and resourceUriComponents. 
 * // w  ww .  j  a  v a  2  s  .c om
 * @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:longism.com.api.APIUtils.java

/**
 * TODO Function: Authenticate, login to sever<br>
 *
 * @param httpClient/*from   ww w.  j  av a 2  s  .co  m*/
 * @param httpRequest
 * @param userName
 * @param password
 * @date: July 07, 2015
 * @author: Nguyen Long
 */
public static void setAuthenticate(DefaultHttpClient httpClient, HttpUriRequest httpRequest, String userName,
        String password) {
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userName, password);
    AuthScope scope = new AuthScope(httpRequest.getURI().getHost(), httpRequest.getURI().getPort());
    httpClient.getCredentialsProvider().setCredentials(scope, credentials);
}

From source file:com.jkoolcloud.tnt4j.streams.inputs.RestStream.java

private static String executeRequest(HttpClient client, HttpUriRequest req, String username, String password)
        throws IOException {
    HttpResponse response;/*from  w w  w . ja v a  2 s .com*/

    if (StringUtils.isNotEmpty(username)) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(req.getURI().getAuthority(), DEFAULT_AUTH_PORT),
                new UsernamePasswordCredentials(username, password));

        HttpClientContext context = HttpClientContext.create();
        context.setCredentialsProvider(credentialsProvider);
        // context.setAuthSchemeRegistry(authRegistry);
        // context.setAuthCache(authCache);

        response = client.execute(req, context);
    } else {
        response = client.execute(req);
    }

    int responseCode = response.getStatusLine().getStatusCode();
    if (responseCode >= HttpStatus.SC_MULTIPLE_CHOICES) {
        throw new HttpResponseException(responseCode, response.getStatusLine().getReasonPhrase());
    }

    String respStr = EntityUtils.toString(response.getEntity(), Utils.UTF8);

    return respStr;
}

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 w w w  .j  av  a 2  s .c o  m
 * 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:org.fcrepo.integration.http.api.AbstractResourceIT.java

/**
 * Execute an HTTP request and close the response.
 *
 * @param req the request to execute/*from  w  ww  .j a  v  a 2  s  .  co 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//  w  w w.j  av a  2s  . 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:com.normalexception.app.rx8club.html.HtmlFormUtils.java

/**
 * Submit a form and its contents/*  w  w w .j a v  a2  s .c om*/
 * @param url       The url to submit the form to
 * @param nvps      The name value pair of the contents
 * @param attachment If true, add attachment headers
 * @return           True if it worked
 * @throws ClientProtocolExecption
 * @throws IOException
 */
private static boolean formSubmit(String url, List<NameValuePair> nvps, boolean attachment)
        throws ClientProtocolException, IOException {
    HttpClient httpclient = LoginFactory.getInstance().getClient();

    HttpPost httpost = ClientUtils.getHttpPost(url);
    Log.d(TAG, "[Submit] Submit URL: " + url);

    // If there is an attachment, we need to add some data
    // to the post header
    if (attachment) {
        String pN = "";
        for (NameValuePair nvp : nvps) {
            if (nvp.getName().equals(VBulletinKeys.PostNumber.getValue())) {
                pN = nvp.getValue();
                break;
            }
        }

        httpost.setHeader("Content-Type", "application/x-www-form-urlencoded");
        httpost.setHeader("Referer", WebUrls.postSubmitAddress + pN);
    }

    httpost.setEntity(new UrlEncodedFormEntity(nvps));

    HttpContext context = LoginFactory.getInstance().getHttpContext();
    HttpResponse response = httpclient.execute(httpost, context);
    HttpEntity entity = response.getEntity();
    StatusLine statusLine = response.getStatusLine();

    Log.d(TAG, "[Submit] Status: " + statusLine.getStatusCode());
    if (entity != null) {
        responseContent = EntityUtils.toString(entity, "UTF-8");

        //httpost.releaseConnection();

        HttpUriRequest request = (HttpUriRequest) context.getAttribute(HttpCoreContext.HTTP_REQUEST);

        responseUrl = request.getURI().toString();
        Log.d(TAG, "[Submit] Response URL: " + responseUrl);

        return true;
    }

    return false;
}

From source file:org.devtcg.five.util.streaming.FailfastHttpClient.java

/**
 * Generates a cURL command equivalent to the given request.
 *//*from  w  w w. ja  v  a2s  .  co m*/
private static String toCurl(HttpUriRequest request) throws IOException {
    StringBuilder builder = new StringBuilder();

    builder.append("curl ");

    for (Header header : request.getAllHeaders()) {
        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:ch.entwine.weblounge.common.impl.util.TestUtils.java

/**
 * Issues the the given request./*from  w w  w  .ja  v  a2  s  .  c  o  m*/
 * 
 * @param httpClient
 *          the http client
 * @param request
 *          the request
 * @param params
 *          the request parameters
 * @throws Exception
 *           if the request fails
 */
public static HttpResponse request(HttpClient httpClient, HttpUriRequest request, String[][] params)
        throws Exception {
    if (params != null) {
        if (request instanceof HttpGet) {
            List<NameValuePair> qparams = new ArrayList<NameValuePair>();
            if (params.length > 0) {
                for (String[] param : params) {
                    if (param.length < 2)
                        continue;
                    qparams.add(new BasicNameValuePair(param[0], param[1]));
                }
            }
            URI requestURI = request.getURI();
            URI uri = URIUtils.createURI(requestURI.getScheme(), requestURI.getHost(), requestURI.getPort(),
                    requestURI.getPath(), URLEncodedUtils.format(qparams, "utf-8"), null);
            HeaderIterator headerIterator = request.headerIterator();
            request = new HttpGet(uri);
            while (headerIterator.hasNext()) {
                request.addHeader(headerIterator.nextHeader());
            }
        } else if (request instanceof HttpPost) {
            List<NameValuePair> formparams = new ArrayList<NameValuePair>();
            for (String[] param : params)
                formparams.add(new BasicNameValuePair(param[0], param[1]));
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "utf-8");
            ((HttpPost) request).setEntity(entity);
        } else if (request instanceof HttpPut) {
            List<NameValuePair> formparams = new ArrayList<NameValuePair>();
            for (String[] param : params)
                formparams.add(new BasicNameValuePair(param[0], param[1]));
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "utf-8");
            ((HttpPut) request).setEntity(entity);
        }
    } else {
        if (request instanceof HttpPost || request instanceof HttpPut) {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(new ArrayList<NameValuePair>(), "utf-8");
            ((HttpEntityEnclosingRequestBase) request).setEntity(entity);
        }
    }
    return httpClient.execute(request);
}