Example usage for org.apache.http.message BasicHttpRequest getRequestLine

List of usage examples for org.apache.http.message BasicHttpRequest getRequestLine

Introduction

In this page you can find the example usage for org.apache.http.message BasicHttpRequest getRequestLine.

Prototype

public RequestLine getRequestLine() 

Source Link

Usage

From source file:cn.heroes.ud.protocol.ElementalHttpGet.java

public static void main(String[] args) throws Exception {
    HttpProcessor httpproc = HttpProcessorBuilder.create().add(new RequestContent())
            .add(new RequestTargetHost()).add(new RequestConnControl()).add(new RequestUserAgent("Test/1.1"))
            .add(new RequestExpectContinue(true)).build();

    HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

    HttpCoreContext coreContext = HttpCoreContext.create();
    HttpHost host = new HttpHost("localhost", 8080);
    coreContext.setTargetHost(host);/*  w w w.  j a v  a  2s .c  o m*/

    DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection(8 * 1024);
    ConnectionReuseStrategy connStrategy = DefaultConnectionReuseStrategy.INSTANCE;

    try {

        String[] targets = { "/", "/servlets-examples/servlet/RequestInfoExample", "/somewhere%20in%20pampa" };

        for (int i = 0; i < targets.length; i++) {
            if (!conn.isOpen()) {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket);
            }
            BasicHttpRequest request = new BasicHttpRequest("GET", targets[i]);
            System.out.println(">> Request URI: " + request.getRequestLine().getUri());

            httpexecutor.preProcess(request, httpproc, coreContext);
            HttpResponse response = httpexecutor.execute(request, conn, coreContext);
            httpexecutor.postProcess(response, httpproc, coreContext);

            System.out.println("<< Response: " + response.getStatusLine());
            System.out.println(EntityUtils.toString(response.getEntity()));
            System.out.println("==============");
            if (!connStrategy.keepAlive(response, coreContext)) {
                conn.close();
            } else {
                System.out.println("Connection kept alive...");
            }
        }
    } finally {
        conn.close();
    }
}

From source file:com.alexjalg.gson_google.EjecutarHttpClient.java

public static void main(String[] args) throws Exception {
    HttpProcessor httpproc = HttpProcessorBuilder.create().add(new RequestContent())
            .add(new RequestTargetHost()).add(new RequestConnControl()).add(new RequestUserAgent("Test/1.1"))
            .add(new RequestExpectContinue(true)).build();

    HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

    HttpCoreContext coreContext = HttpCoreContext.create();
    HttpHost host = new HttpHost("jsonplaceholder.typicode.com", 80);
    coreContext.setTargetHost(host);/* ww  w  . ja  va  2  s  .c  o m*/

    DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection(8 * 1024);
    ConnectionReuseStrategy connStrategy = DefaultConnectionReuseStrategy.INSTANCE;

    try {
        String[] targets = { "/posts" };
        for (int i = 0; i < targets.length; i++) {
            if (!conn.isOpen()) {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket);
            }
            BasicHttpRequest request = new BasicHttpRequest("GET", targets[i]);
            System.out.println(">> Request URI: " + request.getRequestLine().getUri());

            httpexecutor.preProcess(request, httpproc, coreContext);
            HttpResponse response = httpexecutor.execute(request, conn, coreContext);
            httpexecutor.postProcess(response, httpproc, coreContext);

            System.out.println("<< Response: " + response.getStatusLine());

            //                System.out.println(EntityUtils.toString(response.getEntity()));
            String json = EntityUtils.toString(response.getEntity());

            ArrayList<Posts> listPosts = new ArrayList<Posts>();
            Type listType = new TypeToken<ArrayList<Posts>>() {
            }.getType();
            listPosts = new Gson().fromJson(json, listType);

            for (Posts post : listPosts) {
                System.out.println("");
                System.out.println(post.getUserId());
                System.out.println(post.getId());
                System.out.println(post.getTitle());
                System.out.println(post.getBody());
            }

            System.out.println("==============");
            if (!connStrategy.keepAlive(response, coreContext)) {
                conn.close();
            } else {
                System.out.println("Connection kept alive...");
            }
        }
    } finally {
        conn.close();
    }
}

From source file:org.atmosphere.tictactoe42a9x.ElementalHttpGet.java

public static void main(String[] args) throws Exception {

    HttpParams params = new SyncBasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
    HttpProtocolParams.setUseExpectContinue(params, true);

    HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
            // Required protocol interceptors
            new RequestContent(), new RequestTargetHost(),
            // Recommended protocol interceptors
            new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });

    HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

    HttpContext context = new BasicHttpContext(null);
    HttpHost host = new HttpHost("localhost", 8080);

    DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
    ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();

    context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
    context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

    try {/*from w  ww. ja v a2s . c  o  m*/

        String[] targets = { "/", "/servlets-examples/servlet/RequestInfoExample", "/somewhere%20in%20pampa" };

        for (int i = 0; i < targets.length; i++) {
            if (!conn.isOpen()) {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket, params);
            }
            BasicHttpRequest request = new BasicHttpRequest("GET", targets[i]);
            System.out.println(">> Request URI: " + request.getRequestLine().getUri());

            request.setParams(params);
            httpexecutor.preProcess(request, httpproc, context);
            HttpResponse response = httpexecutor.execute(request, conn, context);
            response.setParams(params);
            httpexecutor.postProcess(response, httpproc, context);

            System.out.println("<< Response: " + response.getStatusLine());
            System.out.println(EntityUtils.toString(response.getEntity()));
            System.out.println("==============");
            if (!connStrategy.keepAlive(response, context)) {
                conn.close();
            } else {
                System.out.println("Connection kept alive...");
            }
        }
    } finally {
        conn.close();
    }
}

From source file:net.ElementalHttpGet.java

public static void main(String[] args) throws Exception {

    HttpParams params = new SyncBasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
    HttpProtocolParams.setUseExpectContinue(params, true);

    HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
            // Required protocol interceptors
            new RequestContent(), new RequestTargetHost(),
            // Recommended protocol interceptors
            new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });

    HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

    HttpContext context = new BasicHttpContext(null);
    HttpHost host = new HttpHost("www.baidu.com", 80);

    DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
    ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();

    context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
    context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

    try {/*from   ww  w. j a va2  s . c om*/

        String[] targets = { "/", "/servlets-examples/servlet/RequestInfoExample?a=1&b=2",
                "/somewhere%20in%20pampa" };

        for (int i = 0; i < targets.length; i++) {
            if (!conn.isOpen()) {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket, params);
            }
            BasicHttpRequest request = new BasicHttpRequest("GET", targets[i]);
            System.out.println(">> Request URI: " + request.getRequestLine().getUri());

            request.setParams(params);
            httpexecutor.preProcess(request, httpproc, context);
            HttpResponse response = httpexecutor.execute(request, conn, context);
            response.setParams(params);
            httpexecutor.postProcess(response, httpproc, context);

            System.out.println("<< Response: " + response.getStatusLine());
            System.out.println(EntityUtils.toString(response.getEntity()));
            System.out.println("==============");
            if (!connStrategy.keepAlive(response, context)) {
                conn.close();
            } else {
                System.out.println("Connection kept alive...");
            }
        }
    } finally {
        conn.close();
    }
}

From source file:io.aos.protocol.http.httpcommon.ElementalHttpGet.java

public static void main(String... args) throws Exception {

    HttpParams params = new SyncBasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
    HttpProtocolParams.setUseExpectContinue(params, true);

    HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
            // Required protocol interceptors
            new RequestContent(), new RequestTargetHost(),
            // Recommended protocol interceptors
            new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });

    HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

    HttpContext context = new BasicHttpContext(null);
    HttpHost host = new HttpHost("localhost", 8080);

    DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
    ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();

    context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
    context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

    try {//from  w w  w .  jav  a  2  s  . c o  m

        String[] targets = { "/", "/servlets-examples/servlet/RequestInfoExample", "/somewhere%20in%20pampa" };

        for (int i = 0; i < targets.length; i++) {
            if (!conn.isOpen()) {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket, params);
            }
            BasicHttpRequest request = new BasicHttpRequest("GET", targets[i]);
            System.out.println(">> Request URI: " + request.getRequestLine().getUri());

            request.setParams(params);
            httpexecutor.preProcess(request, httpproc, context);
            HttpResponse response = httpexecutor.execute(request, conn, context);
            response.setParams(params);
            httpexecutor.postProcess(response, httpproc, context);

            System.out.println("<< Response: " + response.getStatusLine());
            System.out.println(EntityUtils.toString(response.getEntity()));
            System.out.println("==============");
            if (!connStrategy.keepAlive(response, context)) {
                conn.close();
            } else {
                System.out.println("Connection kept alive...");
            }
        }
    } finally {
        conn.close();
    }
}

From source file:io.aos.protocol.http.httpcommon.ElementalPoolingHttpGet.java

public static void main(String... args) throws Exception {

    final HttpParams params = new SyncBasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUserAgent(params, "Test/1.1");
    HttpProtocolParams.setUseExpectContinue(params, true);

    final HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
            // Required protocol interceptors
            new RequestContent(), new RequestTargetHost(),
            // Recommended protocol interceptors
            new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });

    final HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

    final BasicConnPool pool = new BasicConnPool(new BasicConnFactory(params));
    pool.setDefaultMaxPerRoute(2);//from   w  w w.ja  v a 2s .  c o m
    pool.setMaxTotal(2);

    HttpHost[] targets = { new HttpHost("www.google.com", 80), new HttpHost("www.yahoo.com", 80),
            new HttpHost("www.apache.com", 80) };

    class WorkerThread extends Thread {

        private final HttpHost target;

        WorkerThread(final HttpHost target) {
            super();
            this.target = target;
        }

        @Override
        public void run() {
            try {
                Future<BasicPoolEntry> future = pool.lease(this.target, null);

                boolean reusable = false;
                BasicPoolEntry entry = future.get();
                try {
                    HttpClientConnection conn = entry.getConnection();
                    HttpContext context = new BasicHttpContext(null);
                    context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
                    context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, this.target);

                    BasicHttpRequest request = new BasicHttpRequest("GET", "/");
                    System.out.println(">> Request URI: " + request.getRequestLine().getUri());

                    request.setParams(params);
                    httpexecutor.preProcess(request, httpproc, context);
                    HttpResponse response = httpexecutor.execute(request, conn, context);
                    response.setParams(params);
                    httpexecutor.postProcess(response, httpproc, context);

                    System.out.println("<< Response: " + response.getStatusLine());
                    System.out.println(EntityUtils.toString(response.getEntity()));

                    ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();
                    reusable = connStrategy.keepAlive(response, context);
                } catch (IOException ex) {
                    throw ex;
                } catch (HttpException ex) {
                    throw ex;
                } finally {
                    if (reusable) {
                        System.out.println("Connection kept alive...");
                    }
                    pool.release(entry, reusable);
                }
            } catch (Exception ex) {
                System.out.println("Request to " + this.target + " failed: " + ex.getMessage());
            }
        }

    }
    ;

    WorkerThread[] workers = new WorkerThread[targets.length];
    for (int i = 0; i < workers.length; i++) {
        workers[i] = new WorkerThread(targets[i]);
    }
    for (int i = 0; i < workers.length; i++) {
        workers[i].start();
    }
    for (int i = 0; i < workers.length; i++) {
        workers[i].join();
    }
}

From source file:proxy.ElementalHttpGet.java

private static void request(HttpProcessor httpproc, HttpRequestExecutor httpexecutor,
        HttpCoreContext coreContext, HttpHost host, InetAddress localinetAddress)
        throws NoSuchAlgorithmException, IOException, HttpException {
    DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection(8 * 1024);
    ConnectionReuseStrategy connStrategy = DefaultConnectionReuseStrategy.INSTANCE;
    try {/* www  .  jav  a2 s . co  m*/

        String[] targets = { "/2/users/show.json?access_token=2.00SlDQsDdcZIJC94e5308f67sRL13D&uid=3550148352",
                "/account/rate_limit_status.json?access_token=2.00SlDQsDdcZIJC94e5308f67sRL13D" };

        for (int i = 0; i < targets.length; i++) {
            if (!conn.isOpen()) {
                SSLContext sslcontext = SSLContext.getInstance("Default");
                //               sslcontext.init(null, null, null);
                SocketFactory sf = sslcontext.getSocketFactory();
                SSLSocket socket = (SSLSocket) sf.createSocket(host.getHostName(), host.getPort(),
                        localinetAddress, 0);
                socket.setEnabledCipherSuites(new String[] { "TLS_RSA_WITH_AES_256_CBC_SHA",
                        "TLS_DHE_RSA_WITH_AES_256_CBC_SHA", "TLS_DHE_DSS_WITH_AES_256_CBC_SHA" });
                conn.bind(socket);
                //               Socket socket = new Socket(host.getHostName(), host.getPort());
                //               conn.bind(socket);
            }
            BasicHttpRequest request = new BasicHttpRequest("GET", targets[i]);
            System.out.println(">> Request URI: " + request.getRequestLine().getUri());

            httpexecutor.preProcess(request, httpproc, coreContext);
            HttpResponse response = httpexecutor.execute(request, conn, coreContext);
            httpexecutor.postProcess(response, httpproc, coreContext);

            System.out.println("<< Response: " + response.getStatusLine());
            System.out.println(EntityUtils.toString(response.getEntity()));
            System.out.println("==============");
            if (!connStrategy.keepAlive(response, coreContext)) {
                conn.close();
            } else {
                System.out.println("Connection kept alive...");
            }
        }
    } finally {
        conn.close();
    }
}

From source file:mpv5.utils.http.HttpClient.java

/**
 * Runs a GET request/*from  ww  w.j  a v  a 2 s  .  c om*/
 * @param srequest The request, eg /servlets-examples/servlet/RequestInfoExample"
 * @return
 * @throws UnknownHostException
 * @throws IOException
 * @throws HttpException
 */
public HttpResponse request(String srequest) throws UnknownHostException, IOException, HttpException {

    if (!conn.isOpen()) {
        Socket socket = new Socket(host.getHostName(), host.getPort());
        conn.bind(socket, params);

        BasicHttpRequest request = new BasicHttpRequest("GET", srequest);
        Log.Debug(this, ">> Request URI: " + request.getRequestLine().getUri());

        request.setParams(params);
        httpexecutor.preProcess(request, httpproc, context);
        HttpResponse response = httpexecutor.execute(request, conn, context);
        response.setParams(params);
        httpexecutor.postProcess(response, httpproc, context);

        //                Log.Debug(this, "<< Response: " + response.getStatusLine());
        //                Log.Debug(this, EntityUtils.toString(response.getEntity()));
        //                Log.Debug(this, "==============");
        //                if (!connStrategy.keepAlive(response, context)) {
        //                    conn.close();
        //                } else {
        //                    Log.Debug(this, "Connection kept alive...");
        //                }
        //            } else {
        //                Log.Debug(this, "Connection already closed.");
        return response;
    }
    return null;
}

From source file:org.jnode.jersey.JNContainer.java

private URI getRequestUri(BasicHttpRequest request, final URI baseUri) {
    try {//  w  w  w  .  j a  va2s . co m
        final String serverAddress = getServerAddress(baseUri);
        String uri = ContainerUtils.getHandlerPath(request.getRequestLine().getUri());
        final String queryString = "";
        if (queryString != null) {
            uri = uri + "?" + ContainerUtils.encodeUnsafeCharacters(queryString);
        }

        return new URI(serverAddress + uri);
    } catch (URISyntaxException ex) {
        throw new IllegalArgumentException(ex);
    }
}

From source file:org.jsnap.http.base.HttpServlet.java

protected void doService(org.apache.http.HttpRequest request, org.apache.http.HttpResponse response)
        throws HttpException, IOException {
    // Client might keep the executing thread blocked for very long unless this header is added.
    response.addHeader(new Header(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE));
    // Create a wrapped request object.
    String uri, data;/*  ww  w.  j  a va2 s .  c  o m*/
    String method = request.getRequestLine().getMethod();
    if (method.equals(HttpGet.METHOD_NAME)) {
        BasicHttpRequest get = (BasicHttpRequest) request;
        data = get.getRequestLine().getUri();
        int ix = data.indexOf('?');
        uri = (ix < 0 ? data : data.substring(0, ix));
        data = (ix < 0 ? "" : data.substring(ix + 1));
    } else if (method.equals(HttpPost.METHOD_NAME)) {
        BasicHttpEntityEnclosingRequest post = (BasicHttpEntityEnclosingRequest) request;
        HttpEntity postedEntity = post.getEntity();
        uri = post.getRequestLine().getUri();
        data = EntityUtils.toString(postedEntity);
    } else {
        response.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED);
        response.setHeader(new Header(HTTP.CONTENT_LEN, "0"));
        return;
    }
    String cookieLine = "";
    if (request.containsHeader(COOKIE)) {
        Header[] cookies = request.getHeaders(COOKIE);
        for (Header cookie : cookies) {
            if (cookieLine.length() > 0)
                cookieLine += "; ";
            cookieLine += cookie.getValue();
        }
    }
    HttpRequest req = new HttpRequest(uri, underlying, data, cookieLine);
    // Create a wrapped response object.
    ByteArrayOutputStream out = new ByteArrayOutputStream(BUFFER_SIZE);
    HttpResponse resp = new HttpResponse(out);
    // Do implementation specific processing.
    doServiceImpl(req, resp);
    out.flush(); // It's good practice to do this.
    // Do the actual writing to the actual response object.
    if (resp.redirectTo != null) {
        // Redirection is requested.
        resp.statusCode = HttpStatus.SC_MOVED_TEMPORARILY;
        response.setStatusCode(resp.statusCode);
        Header redirection = new Header(LOCATION, resp.redirectTo);
        response.setHeader(redirection);
        Logger.getLogger(HttpServlet.class).log(Level.DEBUG,
                "Status Code: " + Integer.toString(resp.statusCode));
        Logger.getLogger(HttpServlet.class).log(Level.DEBUG, redirection.toString());
    } else {
        // There will be a response entity.
        response.setStatusCode(resp.statusCode);
        HttpEntity entity;
        Header contentTypeHeader;
        boolean text = resp.contentType.startsWith(Formatter.TEXT);
        if (text) { // text/* ...
            entity = new StringEntity(out.toString(resp.characterSet), resp.characterSet);
            contentTypeHeader = new Header(HTTP.CONTENT_TYPE,
                    resp.contentType + HTTP.CHARSET_PARAM + resp.characterSet);
        } else { // application/octet-stream, image/* ...
            entity = new ByteArrayEntity(out.toByteArray());
            contentTypeHeader = new Header(HTTP.CONTENT_TYPE, resp.contentType);
        }
        boolean acceptsGzip = clientAcceptsGzip(request);
        long contentLength = entity.getContentLength();
        // If client accepts gzipped content, the implementing object requested that response
        // gets gzipped and size of the response exceeds implementing object's size threshold
        // response entity will be gzipped.
        boolean gzipped = false;
        if (acceptsGzip && resp.zipSize > 0 && contentLength >= resp.zipSize) {
            ByteArrayOutputStream zipped = new ByteArrayOutputStream(BUFFER_SIZE);
            GZIPOutputStream gzos = new GZIPOutputStream(zipped);
            entity.writeTo(gzos);
            gzos.close();
            entity = new ByteArrayEntity(zipped.toByteArray());
            contentLength = zipped.size();
            gzipped = true;
        }
        // This is where true writes are made.
        Header contentLengthHeader = new Header(HTTP.CONTENT_LEN, Long.toString(contentLength));
        Header contentEncodingHeader = null;
        response.setHeader(contentTypeHeader);
        response.setHeader(contentLengthHeader);
        if (gzipped) {
            contentEncodingHeader = new Header(CONTENT_ENCODING, Formatter.GZIP);
            response.setHeader(contentEncodingHeader);
        }
        response.setEntity(entity);
        // Log critical headers.
        Logger.getLogger(HttpServlet.class).log(Level.DEBUG,
                "Status Code: " + Integer.toString(resp.statusCode));
        Logger.getLogger(HttpServlet.class).log(Level.DEBUG, contentTypeHeader.toString());
        if (gzipped)
            Logger.getLogger(HttpServlet.class).log(Level.DEBUG, contentEncodingHeader.toString());
        Logger.getLogger(HttpServlet.class).log(Level.DEBUG, contentLengthHeader.toString());
    }
    // Log cookies.
    for (Cookie cookie : resp.cookies) {
        if (cookie.valid()) {
            Header h = new Header(SET_COOKIE, cookie.toString());
            response.addHeader(h);
            Logger.getLogger(HttpServlet.class).log(Level.DEBUG, h.toString());
        }
    }
}