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.metaeffekt.dcc.agent.DccRequestBuilderTest.java

@Test
public void initialize() {

    HttpUriRequest request = builder.createRequest("initialize", "depId", "somePackage", "someUnit");

    assertCommonParts(request);/*w w  w.  ja v  a2  s .  co  m*/
    assertEquals("PUT", request.getMethod());
    assertEquals("/dcc/depId/packages/somePackage/units/someUnit/initialize", request.getURI().getPath());
}

From source file:io.wcm.caravan.io.http.impl.ResilientHttpImpl.java

private Observable<Response> getHttpObservable(String serviceName, String urlPrefix, Request request) {
    return Observable.<Response>create(new Observable.OnSubscribe<Response>() {

        @Override//from  w w w.  j  a  va  2  s  . c  o m
        public void call(final Subscriber<? super Response> subscriber) {
            HttpUriRequest httpRequest = RequestUtil.buildHttpRequest(urlPrefix, request);

            if (log.isDebugEnabled()) {
                log.debug("Execute: " + httpRequest.getURI() + "\n" + request.toString());
            }

            HttpAsyncClient httpClient = httpClientFactory.getAsync(httpRequest.getURI());
            httpClient.execute(httpRequest, new FutureCallback<HttpResponse>() {

                @Override
                public void completed(HttpResponse result) {
                    StatusLine status = result.getStatusLine();
                    HttpEntity entity = result.getEntity();
                    try {
                        if (status.getStatusCode() >= 500) {
                            subscriber.onError(new IllegalResponseRuntimeException(serviceName, request,
                                    httpRequest.getURI().toString(), status.getStatusCode(),
                                    EntityUtils.toString(entity), "Executing '" + httpRequest.getURI()
                                            + "' failed: " + result.getStatusLine()));
                            EntityUtils.consumeQuietly(entity);
                        } else {
                            Response response = Response.create(status.getStatusCode(),
                                    status.getReasonPhrase(), RequestUtil.toHeadersMap(result.getAllHeaders()),
                                    entity.getContent(),
                                    entity.getContentLength() > 0 ? (int) entity.getContentLength() : null);
                            subscriber.onNext(response);
                            subscriber.onCompleted();
                        }
                    } catch (Throwable ex) {
                        subscriber.onError(new IOException(
                                "Reading response of '" + httpRequest.getURI() + "' failed.", ex));
                        EntityUtils.consumeQuietly(entity);
                    }
                }

                @Override
                public void failed(Exception ex) {
                    if (ex instanceof SocketTimeoutException) {
                        subscriber.onError(new IOException(
                                "Socket timeout executing '" + httpRequest.getURI() + "'.", ex));
                    } else {
                        subscriber.onError(
                                new IOException("Executing '" + httpRequest.getURI() + "' failed.", ex));
                    }
                }

                @Override
                public void cancelled() {
                    subscriber.onError(new IOException("Getting " + httpRequest.getURI() + " was cancelled."));
                }

            });
        }

    });
}

From source file:net.netheos.pcsapi.oauth.OAuth2SessionManager.java

@Override
public CResponse execute(HttpUriRequest request) {
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("{}: {}", request.getMethod(), PcsUtils.shortenUrl(request.getURI()));
    }/*  w ww .  ja  v  a 2  s.c o  m*/

    if (userCredentials.getCredentials().hasExpired()) {
        refreshToken();
    }

    try {
        request.removeHeaders(HEADER_AUTHORIZATION); // in case we are retrying
        request.addHeader(HEADER_AUTHORIZATION, "Bearer " + userCredentials.getCredentials().getAccessToken());

        HttpResponse httpResponse = httpClient.execute(request);
        return new CResponse(request, httpResponse);

    } catch (IOException ex) {
        // a low level error should be retried :
        throw new CRetriableException(ex);
    }
}

From source file:com.sangupta.jerry.http.HttpRateLimitingClient.java

/**
 * The method checks if the current rate execution rate is within the prescribed limits or not
 *///from   w w w.  jav  a  2s .c o m
private void assertRateInLimit(HttpUriRequest request) {
    if (!this.hasHosts) {
        return;
    }

    assertRateInLimit(request.getURI().getHost().toLowerCase());
}

From source file:org.callimachusproject.client.HttpClientRedirectTest.java

/**
 * The interpreted (absolute) URI that was used to generate the last
 * request./*ww  w.  j  av  a 2 s  . c  om*/
 */
private URI getHttpLocation(HttpUriRequest originalRequest, HttpClientContext ctx) {
    try {
        URI original = originalRequest.getURI();
        HttpHost target = ctx.getTargetHost();
        List<URI> redirects = ctx.getRedirectLocations();
        URI absolute = URIUtils.resolve(original, target, redirects);
        return new URI(TermFactory.newInstance(absolute.toASCIIString()).getSystemId());
    } catch (URISyntaxException e) {
        return null;
    }
}

From source file:org.ocpsoft.redoculous.tests.HttpAction.java

/**
 * Return the current full URL./*from   w  w  w .  ja  va 2s .  c  o m*/
 */
public String getCurrentURL() {
    HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
    HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
    String currentUrl = currentHost.toURI() + currentReq.getURI();

    if (currentUrl.startsWith(baseUrl)) {
        currentUrl = currentUrl.substring(baseUrl.length());
    }

    return currentUrl;
}

From source file:org.apache.hadoop.gateway.hdfs.dispatch.WebHdfsHaHttpClientDispatch.java

private void retryRequest(HttpUriRequest outboundRequest, HttpServletRequest inboundRequest,
        HttpServletResponse outboundResponse, HttpResponse inboundResponse, Exception exception)
        throws IOException {
    LOG.retryingRequest(outboundRequest.getURI().toString());
    AtomicInteger counter = (AtomicInteger) inboundRequest.getAttribute(RETRY_COUNTER_ATTRIBUTE);
    if (counter == null) {
        counter = new AtomicInteger(0);
    }/*  ww w  .j  av  a2s.  c o  m*/
    inboundRequest.setAttribute(RETRY_COUNTER_ATTRIBUTE, counter);
    if (counter.incrementAndGet() <= maxRetryAttempts) {
        if (retrySleep > 0) {
            try {
                Thread.sleep(retrySleep);
            } catch (InterruptedException e) {
                LOG.retrySleepFailed(resourceRole, e);
            }
        }
        executeRequest(outboundRequest, inboundRequest, outboundResponse);
    } else {
        LOG.maxRetryAttemptsReached(maxRetryAttempts, resourceRole, outboundRequest.getURI().toString());
        if (inboundResponse != null) {
            writeOutboundResponse(outboundRequest, inboundRequest, outboundResponse, inboundResponse);
        } else {
            throw new IOException(exception);
        }
    }
}

From source file:com.betfair.cougar.client.HttpClientCougarRequestFactoryTest.java

@Test
public void shouldCreateGetRequest() {
    HttpUriRequest httpExchange = factory.create(uri, "GET", mockMessage, mockMarshaller, contentType,
            mockCallContext, mockTimeConstraints);

    assertTrue(httpExchange instanceof HttpGet);
    assertEquals("GET", httpExchange.getMethod());
    assertEquals(uri, httpExchange.getURI().toString());
    assertEquals(5, httpExchange.getAllHeaders().length);
}

From source file:org.elasticsearch.test.rest.client.http.HttpRequestBuilder.java

public HttpResponse execute() throws IOException {
    CloseableHttpResponse closeableHttpResponse = null;
    try {/*  w  w  w . j a  va 2  s.c om*/
        HttpUriRequest httpUriRequest = buildRequest();
        if (logger.isTraceEnabled()) {
            StringBuilder stringBuilder = new StringBuilder(httpUriRequest.getMethod()).append(" ")
                    .append(httpUriRequest.getURI());
            if (Strings.hasLength(body)) {
                stringBuilder.append("\n").append(body);
            }
            logger.trace("sending request \n{}", stringBuilder.toString());
        }
        closeableHttpResponse = httpClient.execute(httpUriRequest);
        HttpResponse httpResponse = new HttpResponse(httpUriRequest, closeableHttpResponse);
        logger.trace("got response \n{}\n{}", closeableHttpResponse,
                httpResponse.hasBody() ? httpResponse.getBody() : "");
        return httpResponse;
    } finally {
        try {
            IOUtils.close(closeableHttpResponse);
        } catch (IOException e) {
            logger.error("error closing http response", e);
        }
    }
}

From source file:com.betfair.cougar.client.HttpClientCougarRequestFactoryTest.java

@Test
public void shouldCreatePostRequest() throws Exception {
    HttpUriRequest httpExchange = factory.create(uri, "POST", mockMessage, mockMarshaller, contentType,
            mockCallContext, mockTimeConstraints);

    assertTrue(httpExchange instanceof HttpPost);
    assertEquals("POST", httpExchange.getMethod());
    assertEquals(uri, httpExchange.getURI().toString());
    assertEquals(5, httpExchange.getAllHeaders().length);
    assertEquals(contentType + "; charset=utf-8",
            ((HttpPost) httpExchange).getEntity().getContentType().getValue());
    assertEquals("some post data", IOUtils.toString(((HttpPost) httpExchange).getEntity().getContent()));
}