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.ambraproject.wombat.service.remote.JsonService.java

/**
 * Send a ReST request and serialize the response to an object. The serialization is controlled by the {@link
 * org.ambraproject.wombat.config.RootConfiguration#gson()} bean.
 *
 * @param target       the REST request to make
 * @param responseType the object type into which to serialize the JSON response
 * @param <T>          the type of {@code responseClass}
 * @return the response, serialized from JSON into an object
 * @throws IOException             if there is an error connecting to the server
 * @throws NullPointerException    if either argument is null
 * @throws EntityNotFoundException if the object at the address does not exist
 *///from  w ww . jav  a  2  s  . co  m
public <T> T requestObject(RemoteService<? extends Reader> remoteService, HttpUriRequest target,
        Type responseType) throws IOException {
    Preconditions.checkNotNull(responseType);
    try (Reader reader = remoteService.request(target)) {
        return deserializeStream(responseType, reader, target.getURI());
    }
}

From source file:com.vmware.photon.controller.nsxclient.RestClientTest.java

@Test
public void testSendGet() {
    ArgumentCaptor<HttpUriRequest> argumentCaptor = setup(RestClient.Method.GET, null);

    HttpUriRequest request = argumentCaptor.getValue();
    assertNotNull(request);//from   w  w w  .  j a va 2 s  .co  m
    assertTrue(request.getMethod().equalsIgnoreCase(RestClient.Method.GET.toString()));
    assertEquals(request.getURI().toString(), target + path);
}

From source file:com.parse.ParseApacheHttpClientTest.java

@Test
public void testGetApacheRequest() throws IOException {
    Map<String, String> headers = new HashMap<>();
    String headerValue = "value";
    headers.put("name", headerValue);

    String url = "http://www.parse.com/";
    String content = "test";
    String contentType = "application/json";
    ParseHttpRequest parseRequest = new ParseHttpRequest.Builder().setUrl(url)
            .setMethod(ParseHttpRequest.Method.POST).setBody(new ParseByteArrayHttpBody(content, contentType))
            .setHeaders(headers).build();

    ParseApacheHttpClient parseClient = new ParseApacheHttpClient(10000, null);
    HttpUriRequest apacheRequest = parseClient.getRequest(parseRequest);

    // Verify method
    assertTrue(apacheRequest instanceof HttpPost);
    // Verify URL
    assertEquals(url, apacheRequest.getURI().toString());
    // Verify Headers
    // We add gzip header to apacheRequest which does not contain in ParseRequest
    assertEquals(2, apacheRequest.getAllHeaders().length);
    assertEquals(1, apacheRequest.getHeaders("name").length);
    assertEquals("name", apacheRequest.getHeaders("name")[0].getName());
    assertEquals(headerValue, apacheRequest.getHeaders("name")[0].getValue());
    // Verify Body
    HttpPost apachePostRequest = (HttpPost) apacheRequest;
    assertEquals(4, apachePostRequest.getEntity().getContentLength());
    assertEquals(contentType, apachePostRequest.getEntity().getContentType().getValue());
    // Can not read parseRequest body to compare since it has been read during
    // creating apacheRequest
    assertArrayEquals(content.getBytes(), ParseIOUtils.toByteArray(apachePostRequest.getEntity().getContent()));
}

From source file:org.ambraproject.wombat.service.remote.JsonService.java

/**
 * Serialize an object either through a REST request or from the cache. If there is a cached value, and the REST
 * service does not indicate that the value has been modified since the value was inserted into the cache, return that
 * value. Else, query the service for JSON and deserialize it to an object as usual.
 *
 * @param cacheKey  the cache parameters object containing the cache key at which to retrieve and store the value
 * @param target       the request to make to the SOA service if the value is not cached
 * @param responseType the type of object to deserialize
 * @param <T>          the type of {@code responseClass}
 * @return the deserialized object//www . j a v  a  2  s . co m
 * @throws IOException
 */
public <T> T requestCachedObject(CachedRemoteService<? extends Reader> remoteService, CacheKey cacheKey,
        HttpUriRequest target, final Type responseType) throws IOException {
    Preconditions.checkNotNull(responseType);
    return remoteService.requestCached(cacheKey, target,
            (Reader reader) -> deserializeStream(responseType, reader, target.getURI()));
}

From source file:com.vmware.photon.controller.nsxclient.RestClientTest.java

@Test
public void testPerformDelete() {
    ArgumentCaptor<HttpUriRequest> argumentCaptor = setup(RestClient.Method.DELETE, null);

    HttpUriRequest request = argumentCaptor.getValue();
    assertNotNull(request);//w  ww .  j av  a 2 s  . c om
    assertTrue(request.getMethod().equalsIgnoreCase(RestClient.Method.DELETE.toString()));
    assertEquals(request.getURI().toString(), target + path);
}

From source file:org.fao.geonet.MockRequestFactoryGeonet.java

@Override
public ClientHttpResponse execute(HttpUriRequest request, Function<HttpClientBuilder, Void> configurator)
        throws IOException {
    final URI uri = request.getURI();
    final Request key = new Request(uri.getHost(), uri.getPort(), uri.getScheme(), null);
    final XmlRequest xmlRequest = (XmlRequest) getRequest(key);
    return new MockClientHttpResponse(Xml.getString(xmlRequest.execute()).getBytes(Constants.CHARSET),
            HttpStatus.OK);// www  .j  a  va2s  .  co  m
}

From source file:org.springframework.cloud.netflix.ribbon.apache.RibbonApacheHttpRequestTests.java

@Test
public void testNullEntity() throws Exception {
    String uri = "http://example.com";
    LinkedMultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
    headers.add("my-header", "my-value");
    headers.add(HttpEncoding.CONTENT_LENGTH, "5192");
    LinkedMultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.add("myparam", "myparamval");
    RibbonApacheHttpRequest httpRequest = new RibbonApacheHttpRequest(new RibbonCommandContext("example", "GET",
            uri, false, headers, params, null, new ArrayList<RibbonRequestCustomizer>()));

    HttpUriRequest request = httpRequest.toRequest(RequestConfig.custom().build());

    assertThat("request is wrong type", request, is(not(instanceOf(HttpEntityEnclosingRequest.class))));
    assertThat("uri is wrong", request.getURI().toString(), startsWith(uri));
    assertThat("my-header is missing", request.getFirstHeader("my-header"), is(notNullValue()));
    assertThat("my-header is wrong", request.getFirstHeader("my-header").getValue(), is(equalTo("my-value")));
    assertThat("Content-Length is wrong", request.getFirstHeader(HttpEncoding.CONTENT_LENGTH).getValue(),
            is(equalTo("5192")));
    assertThat("myparam is missing", request.getURI().getQuery(), is(equalTo("myparam=myparamval")));

}

From source file:com.supernovapps.audio.jstreamsourcer.IcecastTest.java

private HashMap<String, String> getParams(HttpUriRequest request) throws URISyntaxException {
    List<NameValuePair> params = URLEncodedUtils.parse(new URI(request.getURI().toASCIIString()), "UTF-8");
    HashMap<String, String> paramsMap = new HashMap<String, String>();
    for (NameValuePair param : params) {
        paramsMap.put(param.getName(), param.getValue());
    }//from   w  w w. j  a  v  a  2  s.co  m
    return paramsMap;
}

From source file:com.github.avarabyeu.restendpoint.http.DefaultErrorHandler.java

/**
 * Default implementation. May be overridden in subclasses<br>
 * Throws/* w  ww  .ja  v a2s .  com*/
 * {@link com.github.avarabyeu.restendpoint.http.exception.RestEndpointClientException}
 * for client exceptions and
 * {@link com.github.avarabyeu.restendpoint.http.exception.RestEndpointServerException}
 * for server exceptions<br>
 * <p>
 * Throwed exceptions may be overridden in handle* methods
 */
@Override
public void handle(HttpUriRequest rq, HttpResponse rs) throws RestEndpointIOException {
    if (!hasError(rs)) {
        return;
    }
    HttpMethod httpMethod = HttpMethod.valueOf(rq.getMethod());
    URI requestUri = rq.getURI();

    StatusType statusType = StatusType.valueOf(rs.getStatusLine().getStatusCode());
    int statusCode = rs.getStatusLine().getStatusCode();
    String statusMessage = rs.getStatusLine().getReasonPhrase();

    byte[] errorBody = getErrorBody(rs);

    switch (statusType) {
    case CLIENT_ERROR:
        handleClientError(requestUri, httpMethod, statusCode, statusMessage, errorBody);
    case SERVER_ERROR:
        handleServerError(requestUri, httpMethod, statusCode, statusMessage, errorBody);
    default:
        handleDefaultError(requestUri, httpMethod, statusCode, statusMessage, errorBody);
    }
}

From source file:com.norconex.collector.http.redirect.impl.GenericRedirectURLProvider.java

private String toAbsoluteURI(HttpHost host, HttpRequest req) {
    HttpRequest originalReq = req;//from  w  ww  . j a  v a  2 s. co  m

    // Check if we can get full URL from a nested request, to keep
    // the #fragment, if present.
    if (req instanceof HttpRequestWrapper) {
        originalReq = ((HttpRequestWrapper) req).getOriginal();
    }
    if (originalReq instanceof HttpRequestBase) {
        return ((HttpRequestBase) originalReq).getURI().toString();
    }

    // Else, built it
    if (originalReq instanceof HttpUriRequest) {
        HttpUriRequest httpReq = (HttpUriRequest) originalReq;
        if (httpReq.getURI().isAbsolute()) {
            return httpReq.getURI().toString();
        }
        return host.toURI() + httpReq.getURI();
    }

    // if not a friendly type, doing in a more generic way
    RequestLine reqLine = originalReq.getRequestLine();
    if (reqLine != null) {
        return reqLine.getUri();
    }
    return null;
}