Example usage for org.apache.http.client.methods HttpRequestBase getURI

List of usage examples for org.apache.http.client.methods HttpRequestBase getURI

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpRequestBase getURI.

Prototype

public URI getURI() 

Source Link

Document

Returns the original request URI.

Usage

From source file:com.gistlabs.mechanize.PageRequest.java

public HttpResponse consume(final HttpClient client, final HttpRequestBase request) throws Exception {
    if (!wasExecuted) {
        this.client = client;
        this.request = request;

        if (!request.getMethod().equalsIgnoreCase(httpMethod))
            throw new IllegalArgumentException(
                    String.format("Expected %s, but was %s", httpMethod, request.getMethod()));

        if (request.getURI().toString().equals(uri)) {
            HttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), 200, "OK");
            BasicHttpEntity entity = new BasicHttpEntity();
            if (contentLocation != null)
                response.addHeader(new BasicHeader("Content-Location", contentLocation));
            entity.setContentEncoding(charset);
            entity.setContentType(this.contentType);
            entity.setContent(this.body);
            response.setEntity(new BufferedHttpEntity(entity));

            assertParameters(request);//  w w w . ja  v a2s .com
            assertHeaders(request);

            this.wasExecuted = true;
            return response;
        } else {
            assertEquals("URI of the next PageRequest does not match", uri, request.getURI().toString());
            return null;
        }
    } else
        throw new UnsupportedOperationException("Request already executed");
}

From source file:com.alexkli.jhb.Worker.java

@Override
public void run() {
    try {//from  w w w . j av a 2  s. co m
        while (true) {
            long start = System.nanoTime();

            QueueItem<HttpRequestBase> item = queue.take();

            idleAvg.add(System.nanoTime() - start);

            if (item.isPoisonPill()) {
                return;
            }

            HttpRequestBase request = item.getRequest();

            if ("java".equals(config.client)) {
                System.setProperty("http.keepAlive", "false");

                item.sent();

                try {
                    HttpURLConnection http = (HttpURLConnection) new URL(request.getURI().toString())
                            .openConnection();
                    http.setConnectTimeout(5000);
                    http.setReadTimeout(5000);
                    int statusCode = http.getResponseCode();

                    consumeAndCloseStream(http.getInputStream());

                    if (statusCode == 200) {
                        item.done();
                    } else {
                        item.failed();
                    }
                } catch (IOException e) {
                    System.err.println("Failed request: " + e.getMessage());
                    e.printStackTrace();
                    //                        System.exit(2);
                    item.failed();
                }
            } else if ("ahc".equals(config.client)) {
                try {
                    item.sent();

                    try (CloseableHttpResponse response = httpClient.execute(request, context)) {
                        int statusCode = response.getStatusLine().getStatusCode();
                        if (statusCode == 200) {
                            item.done();
                        } else {
                            item.failed();
                        }
                    }
                } catch (IOException e) {
                    System.err.println("Failed request: " + e.getMessage());
                    item.failed();
                }
            } else if ("fast".equals(config.client)) {
                try {
                    URI uri = request.getURI();

                    item.sent();

                    InetAddress addr = InetAddress.getByName(uri.getHost());
                    Socket socket = new Socket(addr, uri.getPort());
                    PrintWriter out = new PrintWriter(socket.getOutputStream());
                    //                        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    // send an HTTP request to the web server
                    out.println("GET / HTTP/1.1");
                    out.append("Host: ").append(uri.getHost()).append(":").println(uri.getPort());
                    out.println("Connection: Close");
                    out.println();
                    out.flush();

                    // read the response
                    consumeAndCloseStream(socket.getInputStream());
                    //                        boolean loop = true;
                    //                        StringBuilder sb = new StringBuilder(8096);
                    //                        while (loop) {
                    //                            if (in.ready()) {
                    //                                int i = 0;
                    //                                while (i != -1) {
                    //                                    i = in.read();
                    //                                    sb.append((char) i);
                    //                                }
                    //                                loop = false;
                    //                            }
                    //                        }
                    item.done();
                    socket.close();

                } catch (IOException e) {
                    e.printStackTrace();
                    item.failed();
                }
            } else if ("nio".equals(config.client)) {
                URI uri = request.getURI();

                item.sent();

                String requestBody = "GET / HTTP/1.1\n" + "Host: " + uri.getHost() + ":" + uri.getPort() + "\n"
                        + "Connection: Close\n\n";

                try {
                    InetSocketAddress addr = new InetSocketAddress(uri.getHost(), uri.getPort());
                    SocketChannel channel = SocketChannel.open();
                    channel.socket().setSoTimeout(5000);
                    channel.connect(addr);

                    ByteBuffer msg = ByteBuffer.wrap(requestBody.getBytes());
                    channel.write(msg);
                    msg.clear();

                    ByteBuffer buf = ByteBuffer.allocate(1024);

                    int count;
                    while ((count = channel.read(buf)) != -1) {
                        buf.flip();

                        byte[] bytes = new byte[count];
                        buf.get(bytes);

                        buf.clear();
                    }
                    channel.close();

                    item.done();

                } catch (IOException e) {
                    e.printStackTrace();
                    item.failed();
                }
            }
        }
    } catch (InterruptedException e) {
        System.err.println("Worker thread [" + this.toString() + "] was interrupted: " + e.getMessage());
    }
}

From source file:de.unwesen.packrat.api.APIBase.java

public byte[] fetchRawSynchronous(HttpRequestBase request, Handler handler) {
    HttpResponse response;//from w w  w  .  j av  a 2  s.com
    try {
        response = sClient.execute(request);

        // Read response
        HttpEntity entity = response.getEntity();
        if (null == entity) {
            Log.e(LTAG, "Response is empty: " + request.getURI().toString());
            if (null != handler) {
                handler.obtainMessage(ERR_EMPTY_RESPONSE).sendToTarget();
            }
            return null;
        }

        return readStreamRaw(entity.getContent());

    } catch (IOException ex) {
        Log.w(LTAG, "An exception occurred when reading the API response: " + ex.getMessage());
        if (null != handler) {
            handler.obtainMessage(ERR_TRANSMISSION).sendToTarget();
        }
        return null;
    }
}

From source file:com.mondora.chargify.controller.ChargifyAdapter.java

protected String executeHttp(HttpRequestBase method) throws ChargifyException, IOException {
    if (logger.isDebugEnabled())
        logger.debug(method.getMethod() + " " + method.getURI().toString());
    HttpResponse response = executeHttpMethod(method);
    return handleResponseCode(response, method);
}

From source file:com.intuit.tank.httpclient4.TankHttpClient4.java

private void sendRequest(BaseRequest request, @Nonnull HttpRequestBase method, String requestBody) {
    String uri = null;//from   w  ww  .j a v a  2 s.co m
    long waitTime = 0L;
    CloseableHttpResponse response = null;
    try {
        uri = method.getURI().toString();
        LOG.debug(request.getLogUtil().getLogMessage(
                "About to " + method.getMethod() + " request to " + uri + " with requestBody  " + requestBody,
                LogEventType.Informational));
        List<String> cookies = new ArrayList<String>();
        if (context.getCookieStore().getCookies() != null) {
            for (Cookie cookie : context.getCookieStore().getCookies()) {
                cookies.add("REQUEST COOKIE: " + cookie.toString());
            }
        }
        request.logRequest(uri, requestBody, method.getMethod(), request.getHeaderInformation(), cookies,
                false);
        setHeaders(request, method, request.getHeaderInformation());
        long startTime = System.currentTimeMillis();
        request.setTimestamp(new Date(startTime));
        response = httpclient.execute(method, context);

        // read response body
        byte[] responseBody = new byte[0];
        // check for no content headers
        if (response.getStatusLine().getStatusCode() != 203 && response.getStatusLine().getStatusCode() != 202
                && response.getStatusLine().getStatusCode() != 204) {
            try {
                InputStream httpInputStream = response.getEntity().getContent();
                responseBody = IOUtils.toByteArray(httpInputStream);
            } catch (Exception e) {
                LOG.warn("could not get response body: " + e);
            }
        }
        long endTime = System.currentTimeMillis();
        processResponse(responseBody, startTime, endTime, request, response.getStatusLine().getReasonPhrase(),
                response.getStatusLine().getStatusCode(), response.getAllHeaders());
        waitTime = endTime - startTime;
    } catch (Exception ex) {
        LOG.error(request.getLogUtil().getLogMessage(
                "Could not do " + method.getMethod() + " to url " + uri + " |  error: " + ex.toString(),
                LogEventType.IO), ex);
        throw new RuntimeException(ex);
    } finally {
        try {
            method.releaseConnection();
            if (response != null) {
                response.close();
            }
        } catch (Exception e) {
            LOG.warn("Could not release connection: " + e, e);
        }
        if (method.getMethod().equalsIgnoreCase("post")
                && request.getLogUtil().getAgentConfig().getLogPostResponse()) {
            LOG.info(request.getLogUtil()
                    .getLogMessage("Response from POST to " + request.getRequestUrl() + " got status code "
                            + request.getResponse().getHttpCode() + " BODY { " + request.getResponse().getBody()
                            + " }", LogEventType.Informational));
        }
    }
    if (waitTime != 0) {
        doWaitDueToLongResponse(request, waitTime, uri);
    }
}

From source file:com.griddynamics.jagger.invoker.http.ApacheAbstractHttpInvoker.java

@Override
public final HttpResponse invoke(Q query, String endpoint) throws InvocationException {
    Preconditions.checkNotNull(query);//from w  w w .  j ava2 s.co  m
    Preconditions.checkNotNull(endpoint);

    HttpRequestBase method = null;
    HttpEntity response = null;
    try {
        method = getHttpMethod(query, endpoint);
        method.setParams(getHttpClientParams(query));

        org.apache.http.HttpResponse httpResponse = httpClient.execute(method);
        response = httpResponse.getEntity();
        return HttpResponse.create(httpResponse.getStatusLine().getStatusCode(),
                EntityUtils.toString(response));
    } catch (Exception e) {
        if (method != null) {
            log.debug("Error during invocation with URL: " + method.getURI() + ", endpoint: " + endpoint
                    + ", query: " + query, e);
        } else {
            log.debug("Error during invocation with: endpoint: " + endpoint + ", query: " + query, e);
        }
        throw new InvocationException("InvocationException : ", e);
    } finally {
        EntityUtils.consumeQuietly(response);
    }
}

From source file:com.mondora.chargify.controller.ChargifyAdapter.java

protected String handleResponseCode(HttpResponse response, HttpRequestBase method) throws ChargifyException {
    StatusLine line = response.getStatusLine();
    String errorMsg = method.getMethod() + " " + String.valueOf(method.getURI()) + " Error "
            + String.valueOf(line.getStatusCode()) + " " + line.getReasonPhrase();
    int code = line.getStatusCode();
    if (isError(code)) {
        try {/*from   www . ja va 2  s. com*/
            Errors error = (Errors) parse(Errors.class, response, method);
            if (error != null) {
                errorMsg = String.valueOf(error) + ". Method " + errorMsg;
            }
        } catch (Exception ex) {
            errorMsg += " " + ex.getMessage() + " " + ex.getStackTrace()[0];
        }
    }
    return handleResponse(code, errorMsg);
}

From source file:com.momock.http.HttpSession.java

public HttpSession(HttpClient httpClient, HttpRequestBase request, IUITaskService uiTaskService,
        IAsyncTaskService asyncTaskService) {
    this.url = request.getURI().toString();
    this.httpClient = httpClient;
    this.request = request;
    this.uiTaskService = uiTaskService;
    this.asyncTaskService = asyncTaskService;
}

From source file:com.emc.storageos.driver.dellsc.scapi.rest.RestClient.java

/**
 * Execute a REST call./*from w w  w  .  ja va  2 s  .com*/
 *
 * @param request The REST request.
 * @return The results from the execution.
 */
private RestResult executeRequest(HttpRequestBase request) {
    RestResult result = null;

    request.addHeader("Accept", "application/json");
    request.addHeader("x-dell-api-version", "2.0");
    request.addHeader("Content-Type", "application/json; charset=utf-8");

    CloseableHttpResponse response = null;
    try {
        response = httpClient.execute(request, httpContext);
        HttpEntity entity = response.getEntity();
        result = new RestResult(request.getURI().toString(), response.getStatusLine().getStatusCode(),
                response.getStatusLine().getReasonPhrase(),
                entity != null ? EntityUtils.toString(response.getEntity()) : "");
    } catch (IOException e) {
        result = new RestResult(500, "Internal Failure", "");
        LOG.warn(String.format("Error in API request: %s", e), e);
    } finally {
        try {
            if (response != null) {
                response.close();
            }
        } catch (IOException e) {
        }
    }

    return result;
}

From source file:com.jzboy.couchdb.http.CouchHttpClient.java

private JsonNode execRequest(HttpRequestBase req, int retry) throws IOException, CouchDBException {
    int attemptsLeft = retry;
    CouchResponse res = null;/*ww  w  .  j a v a  2 s  .  c o m*/
    while (res == null && attemptsLeft > 0) {
        try {
            res = httpclient.execute(req, new CouchResponseHandler());
        } catch (java.net.SocketException se) {
            logger.debug("Got {} on update attempt #{} on {}",
                    new Object[] { se.getMessage(), (3 - attemptsLeft + 1), req.getURI() });
            attemptsLeft--;
        }
    }
    if (res == null)
        throw new CouchDBException(
                String.format("Operation failed after %d attempts: %s", retry, req.getURI()));
    throwOnError(res);
    return res.getBodyAsJson();
}