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.akop.bach.parser.Parser.java

protected String getResponse(HttpUriRequest request, List<NameValuePair> inputs)
        throws IOException, ParserException {
    if (!request.containsHeader("Accept"))
        request.addHeader("Accept", "text/javascript, text/html, application/xml, text/xml, */*");
    if (!request.containsHeader("Accept-Charset"))
        request.addHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");

    if (App.getConfig().logToConsole())
        App.logv("Parser: Fetching %s", request.getURI());

    long started = System.currentTimeMillis();

    initRequest(request);/*from  www.j  a  va2 s  .  co m*/

    try {
        synchronized (mHttpClient) {
            HttpContext context = new BasicHttpContext();

            StringBuilder log = null;

            if (App.getConfig().logHttp()) {
                log = new StringBuilder();

                log.append(String.format("URL: %s\n", request.getURI()));

                log.append("Headers: \n");
                for (Header h : request.getAllHeaders())
                    log.append(String.format("  '%s': '%s'\n", h.getName(), h.getValue()));

                log.append("Cookies: \n");
                for (Cookie c : mHttpClient.getCookieStore().getCookies())
                    log.append(String.format("  '%s': '%s'\n", c.getName(), c.getValue()));

                log.append("Query Elements: \n");

                if (inputs != null) {
                    for (NameValuePair p : inputs)
                        log.append(String.format("  '%s': '%s'\n", p.getName(), p.getValue()));
                } else {
                    log.append("  [empty]\n");
                }
            }

            try {
                mLastResponse = mHttpClient.execute(request, context);
            } catch (SocketTimeoutException e) {
                throw new ParserException(mContext, R.string.error_timed_out);
            }

            try {
                if (mLastResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    HttpUriRequest currentReq = (HttpUriRequest) context
                            .getAttribute(ExecutionContext.HTTP_REQUEST);
                    HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

                    this.mLastUrl = currentHost.toURI() + currentReq.getURI();
                }
            } catch (Exception e) {
                if (App.getConfig().logToConsole()) {
                    App.logv("Unable to get last URL - see stack:");
                    e.printStackTrace();
                }

                this.mLastUrl = null;
            }

            HttpEntity entity = mLastResponse.getEntity();

            if (entity == null)
                return null;

            InputStream stream = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream), 10000);
            StringBuilder builder = new StringBuilder(10000);

            try {
                int read;
                char[] buffer = new char[1000];

                while ((read = reader.read(buffer)) >= 0)
                    builder.append(buffer, 0, read);
            } catch (OutOfMemoryError e) {
                return null;
            }

            stream.close();
            entity.consumeContent();

            String response;

            try {
                response = builder.toString();
            } catch (OutOfMemoryError e) {
                if (App.getConfig().logToConsole())
                    e.printStackTrace();

                return null;
            }

            if (App.getConfig().logHttp()) {
                log.append(String.format("\nResponse: \n%s\n", response));

                writeToFile(
                        generateDatedFilename(
                                "http-log-" + request.getURI().toString().replaceAll("[^A-Za-z0-9]", "_")),
                        log.toString());
            }

            return preparseResponse(response);
        }
    } finally {
        if (App.getConfig().logToConsole())
            displayTimeTaken("Parser: Fetch took", started);
    }
}

From source file:crawlercommons.fetcher.http.SimpleHttpFetcher.java

private String extractRedirectedUrl(String url, HttpContext localContext) {
    // This was triggered by HttpClient with the redirect count was
    // exceeded.//  www. ja  v a  2  s  .c o m
    HttpHost host = (HttpHost) localContext.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
    HttpUriRequest finalRequest = (HttpUriRequest) localContext.getAttribute(HttpCoreContext.HTTP_REQUEST);

    try {
        URL hostUrl = new URI(host.toURI()).toURL();
        return new URL(hostUrl, finalRequest.getURI().toString()).toExternalForm();
    } catch (MalformedURLException e) {
        LOGGER.warn("Invalid host/uri specified in final fetch: " + host + finalRequest.getURI());
        return url;
    } catch (URISyntaxException e) {
        LOGGER.warn("Invalid host/uri specified in final fetch: " + host + finalRequest.getURI());
        return url;
    }
}

From source file:org.hawkular.apm.tests.agent.opentracing.client.http.ApacheHttpClientITest.java

protected void testHttpClientWithoutResponseHandler(HttpUriRequest request, boolean fault, boolean respexpected)
        throws IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {//from   w w w  .j  a v  a  2 s  .  c  o  m
        request.addHeader("test-header", "test-value");
        if (fault) {
            request.addHeader("test-fault", "true");
        }
        if (!respexpected) {
            request.addHeader("test-no-data", "true");
        }

        HttpResponse response = httpclient.execute(request);

        int status = response.getStatusLine().getStatusCode();

        if (!fault) {
            assertEquals("Unexpected response code", 200, status);

            if (respexpected) {
                HttpEntity entity = response.getEntity();

                assertNotNull(entity);

                assertEquals(HELLO_WORLD, EntityUtils.toString(entity));
            }
        } else {
            assertEquals("Unexpected fault response code", 401, status);
        }

    } catch (ConnectException ce) {
        assertEquals(BAD_URL, request.getURI().toString());
    } finally {
        httpclient.close();
    }

    Wait.until(() -> getTracer().finishedSpans().size() == 1);

    List<MockSpan> spans = getTracer().finishedSpans();
    assertEquals(1, spans.size());
    assertEquals(Tags.SPAN_KIND_CLIENT, spans.get(0).tags().get(Tags.SPAN_KIND.getKey()));
    assertEquals(request.getMethod(), spans.get(0).operationName());
    assertEquals(request.getURI().toString(), spans.get(0).tags().get(Tags.HTTP_URL.getKey()));
    if (fault) {
        assertEquals("401", spans.get(0).tags().get(Tags.HTTP_STATUS.getKey()));
    }
}

From source file:org.ecloudmanager.tmrk.cloudapi.CloudapiRequestAuhtorization.java

private String signature(HttpUriRequest request, String apiPrivateKey) {
    StringBuilder sb = new StringBuilder();
    String verb = request.getMethod().toUpperCase();
    String date = request.getFirstHeader(HttpHeaderNames.DATE).getValue();
    Header contentTypeHeader = request.getFirstHeader(HttpHeaderNames.CONTENT_TYPE);
    String contentType = contentTypeHeader != null ? contentTypeHeader.getValue() : null;
    Header contentLengthHeader = request.getFirstHeader(HttpHeaderNames.CONTENT_LENGTH);
    String contentLength = contentLengthHeader != null ? contentLengthHeader.getValue() : null;

    sb.append(verb).append("\n");
    sb.append(contentLength != null ? contentLength.trim() : "").append("\n");
    sb.append(contentType != null ? contentType.trim() : "").append("\n");
    sb.append(date).append("\n");
    HeaderIterator hit = request.headerIterator();
    Headers<Object> headers = new Headers<>();
    while (hit.hasNext()) {
        Header hdr = hit.nextHeader();/*from   w  ww .  jav  a2s .  c o  m*/
        headers.add(hdr.getName(), hdr.getValue());
    }
    sb.append(canonicalizedHeaders(headers));
    sb.append(canonicalizedResource(new ResteasyUriInfo(request.getURI())));

    String sigstr = sb.toString();
    try {
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(getBytes(apiPrivateKey), "HmacSHA256");
        sha256_HMAC.init(secret_key);

        return Base64.encodeBytes(sha256_HMAC.doFinal(getBytes(sigstr)));
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.example.fertilizercrm.common.httpclient.AsyncHttpClient.java

/**
 * Puts a new request in queue as a new thread in pool to be executed
 *
 * @param client          HttpClient to be used for request, can differ in single requests
 * @param contentType     MIME body type, for POST and PUT requests, may be null
 * @param context         Context of Android application, to hold the reference of request
 * @param httpContext     HttpContext in which the request will be executed
 * @param responseHandler ResponseHandler or its subclass to put the response into
 * @param uriRequest      instance of HttpUriRequest, which means it must be of HttpDelete,
 *                        HttpPost, HttpGet, HttpPut, etc.
 * @return RequestHandle of future request process
 *//*w  ww.  jav a 2s .  co m*/
protected RequestHandle sendRequest(DefaultHttpClient client, HttpContext httpContext,
        HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler,
        Context context) {
    if (contentType != null) {
        uriRequest.setHeader("Content-Type", contentType);
    }

    responseHandler.setRequestHeaders(uriRequest.getAllHeaders());
    responseHandler.setRequestURI(uriRequest.getURI());

    Future<?> request = threadPool
            .submit(new AsyncHttpRequest(client, httpContext, uriRequest, responseHandler));

    if (context != null) {
        // Add request to request map
        List<WeakReference<Future<?>>> requestList = requestMap.get(context);
        if (requestList == null) {
            requestList = new LinkedList<WeakReference<Future<?>>>();
            requestMap.put(context, requestList);
        }

        requestList.add(new WeakReference<Future<?>>(request));
    }

    return new RequestHandle(request);
}

From source file:com.socialize.provider.BaseSocializeProvider.java

private HttpResponse executeRequest(HttpClient client, HttpUriRequest request) throws IOException {

    if (logger != null && logger.isDebugEnabled()) {

        StringBuilder builder = new StringBuilder();
        Header[] allHeaders = request.getAllHeaders();

        for (Header header : allHeaders) {
            builder.append(header.getName());
            builder.append(":");
            builder.append(header.getValue());
            builder.append("\n");
        }//from  w  ww  . j av a2 s . c o  m

        if (logger.isDebugEnabled()) {
            logger.debug(
                    "REQUEST \nurl:[" + request.getURI().toString() + "] \nheaders:\n" + builder.toString());

        }

        if (request instanceof HttpPost) {
            HttpPost post = (HttpPost) request;
            HttpEntity entity = post.getEntity();
            String requestData = ioUtils.readSafe(entity.getContent());

            if (logger.isDebugEnabled()) {
                logger.debug("REQUEST \ndata:[" + requestData + "]");
            }
        }
    }

    return client.execute(request);
}

From source file:org.hawkular.apm.tests.agent.opentracing.client.http.ApacheHttpClientITest.java

protected void testHttpClientWithResponseHandler(HttpUriRequest request, boolean fault) throws IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*w w w.j  a  v  a2 s .  c  o m*/
        request.addHeader("test-header", "test-value");
        if (fault) {
            request.addHeader("test-fault", "true");
        }

        // Create a custom response handler
        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

            @Override
            public String handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();

                assertEquals("Unexpected response code", 200, status);

                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            }

        };

        String responseBody = httpclient.execute(request, responseHandler);

        assertEquals(HELLO_WORLD, responseBody);

    } catch (ConnectException ce) {
        assertEquals(BAD_URL, request.getURI().toString());
    } finally {
        httpclient.close();
    }

    Wait.until(() -> getTracer().finishedSpans().size() == 1);

    List<MockSpan> spans = getTracer().finishedSpans();
    assertEquals(1, spans.size());
    assertEquals(Tags.SPAN_KIND_CLIENT, spans.get(0).tags().get(Tags.SPAN_KIND.getKey()));
    assertEquals(request.getMethod(), spans.get(0).operationName());
    assertEquals(request.getURI().toString(), spans.get(0).tags().get(Tags.HTTP_URL.getKey()));
    if (fault) {
        assertEquals("401", spans.get(0).tags().get(Tags.HTTP_STATUS.getKey()));
    }
}

From source file:com.aoeng.degu.utils.net.asyncthhpclient.AsyncHttpClient.java

/**
 * Puts a new request in queue as a new thread in pool to be executed
 *
 * @param client          HttpClient to be used for request, can differ in single requests
 * @param contentType     MIME body type, for POST and PUT requests, may be null
 * @param context         Context of Android application, to hold the reference of request
 * @param httpContext     HttpContext in which the request will be executed
 * @param responseHandler ResponseHandler or its subclass to put the response into
 * @param uriRequest      instance of HttpUriRequest, which means it must be of HttpDelete,
 *                        HttpPost, HttpGet, HttpPut, etc.
 * @return RequestHandle of future request process
 *///from   ww w  .ja  va2 s . com
protected RequestHandle sendRequest(DefaultHttpClient client, HttpContext httpContext,
        HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler,
        Context context) {
    if (contentType != null) {
        uriRequest.setHeader("Content-Type", contentType);
    }

    responseHandler.setRequestHeaders(uriRequest.getAllHeaders());
    responseHandler.setRequestURI(uriRequest.getURI());

    Future<?> request = threadPool
            .submit(new AsyncHttpRequest(client, httpContext, uriRequest, responseHandler));

    if (context != null) {
        // Add request to request map
        List<WeakReference<Future<?>>> requestList = requestMap.get(context);
        if (requestList == null) {
            requestList = new LinkedList<WeakReference<Future<?>>>();
            requestMap.put(context, requestList);
        }

        requestList.add(new WeakReference<Future<?>>(request));

        // TODO: Remove dead weakrefs from requestLists?
    }

    return new RequestHandle(request);
}

From source file:jetbrains.buildServer.commitPublisher.github.api.impl.GitHubApiImpl.java

@NotNull
private <T> T processResponse(@NotNull HttpUriRequest request, @NotNull final Class<T> clazz)
        throws IOException {
    setDefaultHeaders(request);//from   w ww  .j a  va2  s.c o m
    try {
        logRequest(request, null);

        final HttpResponse execute = myClient.execute(request);
        if (execute.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_OK) {
            logFailedResponse(request, null, execute);
            throw new IOException("Failed to complete request to GitHub. Status: " + execute.getStatusLine());
        }

        final HttpEntity entity = execute.getEntity();
        if (entity == null) {
            logFailedResponse(request, null, execute);
            throw new IOException(
                    "Failed to complete request to GitHub. Empty response. Status: " + execute.getStatusLine());
        }

        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            entity.writeTo(bos);
            final String json = bos.toString("utf-8");
            LOG.debug("Parsing json for " + request.getURI().toString() + ": " + json);
            return myGson.fromJson(json, clazz);
        } finally {
            EntityUtils.consume(entity);
        }
    } finally {
        request.abort();
    }
}

From source file:cn.rongcloud.im.server.network.http.AsyncHttpClient.java

/**
 * Puts a new request in queue as a new thread in pool to be executed
 *
 * @param client          HttpClient to be used for request, can differ in single requests
 * @param contentType     MIME body type, for POST and PUT requests, may be null
 * @param context         Context of Android application, to hold the reference of request
 * @param httpContext     HttpContext in which the request will be executed
 * @param responseHandler ResponseHandler or its subclass to put the response into
 * @param uriRequest      instance of HttpUriRequest, which means it must be of HttpDelete,
 *                        HttpPost, HttpGet, HttpPut, etc.
 * @return RequestHandle of future request process
 *///from  w  w  w .j a v a  2 s  .com
protected RequestHandle sendRequest(DefaultHttpClient client, HttpContext httpContext,
        HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler,
        Context context) {
    if (contentType != null) {
        uriRequest.addHeader("Content-Type", contentType);
    }

    responseHandler.setRequestHeaders(uriRequest.getAllHeaders());
    responseHandler.setRequestURI(uriRequest.getURI());

    Future<?> request = threadPool
            .submit(new AsyncHttpRequest(client, httpContext, uriRequest, responseHandler));

    if (context != null) {
        // Add request to request map
        List<WeakReference<Future<?>>> requestList = requestMap.get(context);
        if (requestList == null) {
            requestList = new LinkedList<WeakReference<Future<?>>>();
            requestMap.put(context, requestList);
        }

        requestList.add(new WeakReference<Future<?>>(request));

        // TODO: Remove dead weakrefs from requestLists?
    }

    return new RequestHandle(request);
}