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.piusvelte.sonet.core.SonetHttpClient.java

protected static String httpResponse(HttpClient httpClient, HttpUriRequest httpRequest) {
    String response = null;//  w ww . j  a v a  2 s.c o m
    if (httpClient != null) {
        HttpResponse httpResponse;
        HttpEntity entity = null;
        try {
            httpResponse = httpClient.execute(httpRequest);
            StatusLine statusLine = httpResponse.getStatusLine();
            entity = httpResponse.getEntity();

            switch (statusLine.getStatusCode()) {
            case 200:
            case 201:
            case 204:
                if (entity != null) {
                    InputStream is = entity.getContent();
                    ByteArrayOutputStream content = new ByteArrayOutputStream();
                    byte[] sBuffer = new byte[512];
                    int readBytes = 0;
                    while ((readBytes = is.read(sBuffer)) != -1) {
                        content.write(sBuffer, 0, readBytes);
                    }
                    response = new String(content.toByteArray());
                } else {
                    response = "OK";
                }
                break;
            default:
                Log.e(TAG, httpRequest.getURI().toString());
                Log.e(TAG, "" + statusLine.getStatusCode() + " " + statusLine.getReasonPhrase());
                if (entity != null) {
                    InputStream is = entity.getContent();
                    ByteArrayOutputStream content = new ByteArrayOutputStream();
                    byte[] sBuffer = new byte[512];
                    int readBytes = 0;
                    while ((readBytes = is.read(sBuffer)) != -1) {
                        content.write(sBuffer, 0, readBytes);
                    }
                    Log.e(TAG, "response:" + new String(content.toByteArray()));
                }
                break;
            }
        } catch (ClientProtocolException e) {
            Log.e(TAG, e.toString());
            try {
                httpRequest.abort();
            } catch (UnsupportedOperationException ignore) {
                Log.e(TAG, ignore.toString());
            }
        } catch (IllegalStateException e) {
            Log.e(TAG, e.toString());
            try {
                httpRequest.abort();
            } catch (UnsupportedOperationException ignore) {
                Log.e(TAG, ignore.toString());
            }
        } catch (IOException e) {
            Log.e(TAG, e.toString());
            try {
                httpRequest.abort();
            } catch (UnsupportedOperationException ignore) {
                Log.e(TAG, ignore.toString());
            }
        } finally {
            if (entity != null) {
                try {
                    entity.consumeContent();
                } catch (IOException e) {
                    Log.e(TAG, e.toString());
                }
            }
        }
    }
    return response;
}

From source file:org.mycontroller.restclient.core.RestHttpClient.java

private RestHttpResponse execute(HttpUriRequest request) {
    CloseableHttpResponse response = null;
    try {/* w w w.  j a  va 2 s.  c om*/
        response = client.execute(request);
        return RestHttpResponse.get(request.getURI(), response);
    } catch (Exception ex) {
        _logger.debug("Exception,", ex);
        throw new RuntimeException(
                MessageFormat.format("Failed to execute, Request:{0}, error:{1}", request, ex.getMessage()));
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException ex) {
                _logger.error("Exception,", ex);
            }
        }
    }
}

From source file:ch.cyberduck.core.sds.provider.HttpComponentsConnector.java

@Override
public ClientResponse apply(final ClientRequest clientRequest) throws ProcessingException {
    final HttpUriRequest request = this.toUriHttpRequest(clientRequest);
    final Map<String, String> clientHeadersSnapshot = writeOutBoundHeaders(clientRequest.getHeaders(), request);

    try {//from   w  w w . j  a v a 2  s  . co m
        final CloseableHttpResponse response;
        response = client.execute(new HttpHost(request.getURI().getHost(), request.getURI().getPort(),
                request.getURI().getScheme()), request, new BasicHttpContext(context));
        HeaderUtils.checkHeaderChanges(clientHeadersSnapshot, clientRequest.getHeaders(),
                this.getClass().getName());

        final Response.StatusType status = response.getStatusLine().getReasonPhrase() == null
                ? Statuses.from(response.getStatusLine().getStatusCode())
                : Statuses.from(response.getStatusLine().getStatusCode(),
                        response.getStatusLine().getReasonPhrase());

        final ClientResponse responseContext = new ClientResponse(status, clientRequest);
        final List<URI> redirectLocations = context.getRedirectLocations();
        if (redirectLocations != null && !redirectLocations.isEmpty()) {
            responseContext.setResolvedRequestUri(redirectLocations.get(redirectLocations.size() - 1));
        }

        final Header[] respHeaders = response.getAllHeaders();
        final MultivaluedMap<String, String> headers = responseContext.getHeaders();
        for (final Header header : respHeaders) {
            final String headerName = header.getName();
            List<String> list = headers.get(headerName);
            if (list == null) {
                list = new ArrayList<>();
            }
            list.add(header.getValue());
            headers.put(headerName, list);
        }

        final HttpEntity entity = response.getEntity();

        if (entity != null) {
            if (headers.get(HttpHeaders.CONTENT_LENGTH) == null) {
                headers.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(entity.getContentLength()));
            }

            final Header contentEncoding = entity.getContentEncoding();
            if (headers.get(HttpHeaders.CONTENT_ENCODING) == null && contentEncoding != null) {
                headers.add(HttpHeaders.CONTENT_ENCODING, contentEncoding.getValue());
            }
        }
        responseContext.setEntityStream(this.toInputStream(response));
        return responseContext;
    } catch (final Exception e) {
        throw new ProcessingException(e);
    }
}

From source file:net.sourceforge.jwbf.core.actions.HttpActionClient.java

private String debugRequestPathOf(HttpUriRequest request) {
    String requestString = request.getURI().toString();
    int lastSlash = requestString.lastIndexOf("/");
    requestString = requestString.substring(0, lastSlash);
    return requestString;
}

From source file:com.comcast.cim.rest.client.xhtml.TestRequestBuilder.java

@Test
public void testCanBuildRequestForAbsoluteLinkHref() throws Exception {
    Element a = new Element("a", XhtmlParser.XHTML_NS_URI);
    String absoluteUri = "http://www.example.com/foo";
    a.setAttribute("href", absoluteUri);
    buildDocument(a);/* w w w.j a va 2s.c  o  m*/
    URL context = new URL("http://bar.example.com/");
    HttpUriRequest result = impl.followLink(a, context);
    Assert.assertNotNull(result);
    Assert.assertEquals("GET", result.getMethod());
    Assert.assertEquals(absoluteUri, result.getURI().toString());
}

From source file:org.greencheek.spring.rest.SSLCachingHttpComponentsClientHttpResponse.java

public String getFinalUri() {
    String url = finalUri.get();//w  w w. java 2  s.  c o m
    if (url != null)
        return url;

    HttpHost host = (HttpHost) this.httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
    HttpUriRequest finalRequest = (HttpUriRequest) this.httpContext.getAttribute(ExecutionContext.HTTP_REQUEST);

    StringBuilder finalUriString = new StringBuilder();

    finalUriString.append(host.getSchemeName()).append("://");
    finalUriString.append(host.getHostName());
    if (host.getPort() != -1) {
        finalUriString.append(':').append(host.getPort());
    }
    finalUriString.append(finalRequest.getURI().normalize().toString());
    finalUri.compareAndSet(null, finalUriString.toString());
    return finalUri.get();
}

From source file:net.heroicefforts.viable.android.rep.it.gdata.ProjectHostingService.java

/**
 * Wraps the request in authentication and gzip headers before executing it.
 * //w ww.  j a  va  2 s.  c om
 * @param request the request to be executed.
 * @return the client response
 * @throws IOException if an error occurs
 */
private HttpResponse execute(HttpUriRequest request) throws IOException {
    if (Config.LOGV)
        Log.v(TAG, "Requesting:  " + request.getURI().toASCIIString());
    request.addHeader("Accept-Encoding", "gzip");
    if (authToken != null) {
        request.addHeader("Authorization", "GoogleLogin auth=" + authToken);
        //         request.addHeader("Authorization", "AuthSub token=" + authToken);
        if (Config.LOGV)
            Log.v(TAG, "Added auth token '" + authToken + "' to request.");
    }
    return httpclient.execute(request);
}

From source file:com.hp.octane.integrations.services.rest.OctaneRestClientImpl.java

private OctaneResponse login(OctaneConfiguration config) throws IOException {
    OctaneResponse result;/*from   ww  w  .  jav  a 2 s  . c  o  m*/
    HttpResponse response = null;

    try {
        HttpUriRequest loginRequest = buildLoginRequest(config);
        HttpClientContext context = createHttpContext(loginRequest.getURI().toString(), true);
        response = httpClient.execute(loginRequest, context);

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            refreshSecurityToken(context, true);
        } else {
            logger.warn("failed to login to " + config + "; response status: "
                    + response.getStatusLine().getStatusCode());
        }
        result = createNGAResponse(response);
    } catch (IOException ioe) {
        logger.debug("failed to login to " + config, ioe);
        throw ioe;
    } finally {
        if (response != null) {
            EntityUtils.consumeQuietly(response.getEntity());
            HttpClientUtils.closeQuietly(response);
        }
    }

    return result;
}

From source file:com.pyj.http.AsyncHttpRequest.java

public AsyncHttpRequest(AbstractHttpClient client, HttpContext context, HttpUriRequest request,
        AsyncHttpResponseHandler responseHandler, int reqType) {
    this.client = client;
    this.context = context;
    this.request = request;
    this.responseHandler = responseHandler;
    this.reqType = reqType;
    if (responseHandler instanceof BinaryHttpResponseHandler) {
        this.isBinaryRequest = true;
    }// ww  w .java2s .  c  o  m
    HupuLog.d(request.getURI().toString());
}

From source file:com.jaeksoft.searchlib.crawler.web.spider.HttpAbstract.java

public URI getRedirectLocation() {
    synchronized (this) {
        if (httpResponse == null)
            return null;
        if (httpClientContext == null)
            return null;
        try {//from  w ww.j av a 2  s.com
            if (!redirectStrategy.isRedirected(httpBaseRequest, httpResponse, httpClientContext))
                return null;
            HttpUriRequest httpUri = redirectStrategy.getRedirect(httpBaseRequest, httpResponse,
                    httpClientContext);
            if (httpUri == null)
                return null;
            return httpUri.getURI();
        } catch (ProtocolException e) {
            Logging.error(e);
            return null;
        }
    }
}