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:org.datacleaner.util.http.CASMonitorHttpClientTest.java

private static void doRequest(CASMonitorHttpClient client, HttpUriRequest req) throws Exception {
    System.out.println("REQUESTING: " + req.getURI());

    final HttpResponse response = client.execute(req);

    final StatusLine statusLine = response.getStatusLine();
    System.out.println("\tStatus: " + statusLine.getStatusCode() + " - " + statusLine.getReasonPhrase());

    final HttpEntity entity = response.getEntity();
    final InputStream in = entity.getContent();

    final BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    String line = reader.readLine();
    while (line != null) {
        System.out.println("\t" + line);
        line = reader.readLine();//from w  ww . j a  v  a2  s  .  c  o  m
    }
}

From source file:com.microsoft.windowsazure.core.pipeline.apache.HttpServiceRequestContext.java

private static URI tryGetFullURI(HttpRequest request) {
    if (!(request instanceof HttpUriRequest)) {
        return null;
    }//from w w  w  . j a  v  a 2 s  . c o  m
    HttpUriRequest uriRequest = (HttpUriRequest) request;
    URI uri = uriRequest.getURI();
    return isFullURI(uri) ? uri : null;
}

From source file:tech.sirwellington.alchemy.http.VerbAssertions.java

private static void assertRequestWith(HttpVerb verb, Class<? extends HttpUriRequest> type) throws Exception {
    HttpClient mockClient = mock(HttpClient.class);
    when(mockClient.execute(any(HttpUriRequest.class))).thenReturn(createFakeApacheResponse());

    URI uri = createFakeUri();/*from w  ww .  j  a v  a2  s .c om*/

    HttpRequest request = HttpRequest.Builder.newInstance().usingUrl(uri.toURL()).build();

    verb.execute(mockClient, request);

    ArgumentCaptor<HttpUriRequest> captor = forClass(HttpUriRequest.class);

    verify(mockClient).execute(captor.capture());

    HttpUriRequest requestMade = captor.getValue();

    assertThat(requestMade, notNullValue());
    assertThat(requestMade.getURI(), is(uri));
    assertThat(requestMade.getClass(), sameInstance(type));
}

From source file:org.yamj.core.tools.web.PoolingHttpClient.java

private static HttpHost determineTarget(HttpUriRequest request) throws ClientProtocolException {
    HttpHost target = null;//from  w  w w.ja v  a 2 s .  c o  m
    URI requestURI = request.getURI();
    if (requestURI.isAbsolute()) {
        target = URIUtils.extractHost(requestURI);
        if (target == null) {
            throw new ClientProtocolException("URI does not specify a valid host name: " + requestURI);
        }
    }
    return target;
}

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

/**
 * Call before an invocation/*  w ww . jav  a2  s.  co  m*/
 *
 * @param aRequest
 *        The request to be executed. May not be <code>null</code>.
 * @param aHttpContext
 *        The special HTTP content for this call. May be <code>null</code>.
 */
public static void beforeRequest(@Nonnull final HttpUriRequest aRequest,
        @Nullable final HttpContext aHttpContext) {
    if (isEnabled())
        if (LOGGER.isInfoEnabled())
            LOGGER.info("Before HTTP call: " + aRequest.getMethod() + " " + aRequest.getURI()
                    + (aHttpContext != null ? " (with special HTTP context)" : ""));
}

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

/**
 * Create a canonicalized string with the httpRequest and resourceUriComponents. 
 * // ww w. j  a v a 2 s.co 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;
    return canonicalizeHttpRequest(rq.getURI(), uriComponents, rq.getMethod(),
            HttpUtilities.parseRequestContentType(rq), Utilities.emptyString(),
            HttpUtilities.parseHttpHeaders(rq));
}

From source file:org.apache.gobblin.HttpTestUtils.java

public static void assertEqual(RequestBuilder actual, RequestBuilder expect) throws IOException {
    // Check entity
    HttpEntity actualEntity = actual.getEntity();
    HttpEntity expectedEntity = expect.getEntity();
    if (actualEntity == null) {
        Assert.assertTrue(expectedEntity == null);
    } else {/*  w  w  w  .j  av a2s. c  o m*/
        Assert.assertEquals(actualEntity.getContentLength(), expectedEntity.getContentLength());
        String actualContent = IOUtils.toString(actualEntity.getContent(), StandardCharsets.UTF_8);
        String expectedContent = IOUtils.toString(expectedEntity.getContent(), StandardCharsets.UTF_8);
        Assert.assertEquals(actualContent, expectedContent);
    }

    // Check request
    HttpUriRequest actualRequest = actual.build();
    HttpUriRequest expectedRequest = expect.build();
    Assert.assertEquals(actualRequest.getMethod(), expectedRequest.getMethod());
    Assert.assertEquals(actualRequest.getURI().toString(), expectedRequest.getURI().toString());

    Header[] actualHeaders = actualRequest.getAllHeaders();
    Header[] expectedHeaders = expectedRequest.getAllHeaders();
    Assert.assertEquals(actualHeaders.length, expectedHeaders.length);
    for (int i = 0; i < actualHeaders.length; i++) {
        Assert.assertEquals(actualHeaders[i].toString(), expectedHeaders[i].toString());
    }
}

From source file:com.netflix.spinnaker.orca.pipeline.util.HttpClientUtils.java

private static CloseableHttpClient httpClientWithServiceUnavailableRetryStrategy() {
    HttpClientBuilder httpClientBuilder = HttpClients.custom()
            .setServiceUnavailableRetryStrategy(new ServiceUnavailableRetryStrategy() {
                @Override//  ww  w.  ja  v a 2  s .  com
                public boolean retryRequest(HttpResponse response, int executionCount, HttpContext context) {
                    int statusCode = response.getStatusLine().getStatusCode();
                    HttpUriRequest currentReq = (HttpUriRequest) context
                            .getAttribute(HttpCoreContext.HTTP_REQUEST);
                    LOGGER.info("Response code {} for {}", statusCode, currentReq.getURI());

                    if (statusCode >= HttpStatus.SC_OK && statusCode <= 299) {
                        return false;
                    }

                    boolean shouldRetry = (statusCode == 429
                            || RETRYABLE_500_HTTP_STATUS_CODES.contains(statusCode))
                            && executionCount <= MAX_RETRIES;
                    if (!shouldRetry) {
                        throw new RetryRequestException(String.format("Not retrying %s. Count %d, Max %d",
                                currentReq.getURI(), executionCount, MAX_RETRIES));
                    }

                    LOGGER.error("Retrying request on response status {}. Count {} Max is {}", statusCode,
                            executionCount, MAX_RETRIES);
                    return true;
                }

                @Override
                public long getRetryInterval() {
                    return RETRY_INTERVAL;
                }
            });

    httpClientBuilder.setRetryHandler((exception, executionCount, context) -> {
        HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(HttpCoreContext.HTTP_REQUEST);
        Uninterruptibles.sleepUninterruptibly(RETRY_INTERVAL, TimeUnit.MILLISECONDS);
        LOGGER.info("Encountered network error. Retrying request {},  Count {} Max is {}", currentReq.getURI(),
                executionCount, MAX_RETRIES);
        return executionCount <= MAX_RETRIES;
    });

    httpClientBuilder.setDefaultRequestConfig(RequestConfig.custom().setConnectionRequestTimeout(TIMEOUT_MILLIS)
            .setConnectTimeout(TIMEOUT_MILLIS).setSocketTimeout(TIMEOUT_MILLIS).build());

    return httpClientBuilder.build();
}

From source file:com.vaushell.superpipes.tools.HTTPhelper.java

/**
 * Return all redirected URLs.//from   www  . j a va 2 s  .com
 *
 * @param builder Http client builder
 * @param source Source URI
 * @return a list of redirected URLs
 * @throws IOException
 */
public static List<URI> getRedirected(final HttpClientBuilder builder, final URI source) throws IOException {
    if (builder == null || source == null) {
        throw new IllegalArgumentException();
    }

    final List<URI> uris = new ArrayList<>();

    builder.setRedirectStrategy(new DefaultRedirectStrategy() {

        @Override
        public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response,
                final HttpContext context) throws ProtocolException {
            final HttpUriRequest r = super.getRedirect(request, response, context);

            uris.add(r.getURI());

            return r;
        }

    }).build();

    try (final CloseableHttpClient client = builder.build()) {
        final HttpGet get = new HttpGet(source);

        client.execute(get);

        get.abort();
    }

    return uris;
}

From source file:com.tfm.utad.sqoopdata.SqoopVerticaDB.java

private static void sendDataToCartoDB(List<CoordinateCartoDB> result) {

    String url = "http://jab-utad.cartodb.com/api/v2/sql?q=";
    String api = "&api_key=00ffbd3278c07285554983d9713bc08c18d461b3";
    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response;/*from w  w w  .  j  ava  2  s  .c  om*/
    try {
        StringBuilder sb = new StringBuilder();
        sb.append(
                "INSERT INTO tfm_utad_wearables (_offset, userstr, created_date, activity, latitude, longitude, userid) VALUES ");
        for (int i = 0; i < result.size(); i++) {
            CoordinateCartoDB coordinateCartoDB = result.get(i);
            String date = coordinateCartoDB.getCreated_date().replace(' ', 'T');
            String insert;
            if (i < result.size() - 1) {
                insert = "(" + coordinateCartoDB.getOffset() + ",'" + coordinateCartoDB.getUserstr() + "','"
                        + date + "','" + coordinateCartoDB.getActivity() + "',"
                        + String.valueOf(coordinateCartoDB.getLatitude()) + ","
                        + String.valueOf(coordinateCartoDB.getLongitude()) + "," + coordinateCartoDB.getUserid()
                        + "),";
            } else {
                insert = "(" + coordinateCartoDB.getOffset() + ",'" + coordinateCartoDB.getUserstr() + "','"
                        + date + "','" + coordinateCartoDB.getActivity() + "',"
                        + String.valueOf(coordinateCartoDB.getLatitude()) + ","
                        + String.valueOf(coordinateCartoDB.getLongitude()) + "," + coordinateCartoDB.getUserid()
                        + ")";
            }
            sb.append(insert);
        }
        String encode = URLEncoder.encode(sb.toString(), HTTP.UTF_8).replaceAll("\\+", "%20")
                .replaceAll("\\%21", "!").replaceAll("\\%27", "'").replaceAll("\\%28", "(")
                .replaceAll("\\%29", ")").replaceAll("\\%2C", ",").replaceAll("\\%3A", ":")
                .replaceAll("\\%27", "'").replaceAll("\\%7E", "~");
        URI uri = new URI(url + encode + api);
        HttpUriRequest request = new HttpGet(uri);
        LOG.info("Request sending to CartoDB...:" + request.getURI().toString());
        response = httpclient.execute(request);
        LOG.info("Response code:" + response.getStatusLine());
    } catch (UnsupportedEncodingException ex) {
        LOG.error("UnsupportedEncodingException:" + ex.toString());
    } catch (IOException ex) {
        LOG.error("IOException:" + ex.toString());
    } catch (URISyntaxException ex) {
        LOG.error("URISyntaxException:" + ex.toString());
    }
}