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

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

Introduction

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

Prototype

public BasicHttpRequest(String str, String str2) 

Source Link

Usage

From source file:com.bosch.cr.integration.hello_world_ui.ProxyServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String auth = req.getHeader("Authorization");
    if (auth == null) {
        resp.setHeader("WWW-Authenticate", "BASIC realm=\"Proxy for CR\"");
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;/*from  ww w .  j a va2 s.  c  o  m*/
    }

    try {
        long time = System.currentTimeMillis();
        CloseableHttpClient c = getHttpClient();

        String targetUrl = URL_PREFIX + req.getPathInfo()
                + (req.getQueryString() != null ? ("?" + req.getQueryString()) : "");
        BasicHttpRequest targetReq = new BasicHttpRequest(req.getMethod(), targetUrl);

        String user = "";
        if (auth.toUpperCase().startsWith("BASIC ")) {
            String userpassDecoded = new String(
                    new sun.misc.BASE64Decoder().decodeBuffer(auth.substring("BASIC ".length())));
            user = userpassDecoded.substring(0, userpassDecoded.indexOf(':'));
            String pass = userpassDecoded.substring(userpassDecoded.indexOf(':') + 1);
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass);
            targetReq.addHeader(new BasicScheme().authenticate(creds, targetReq, null));
        }

        targetReq.addHeader("x-cr-api-token", req.getHeader("x-cr-api-token"));
        CloseableHttpResponse targetResp = c.execute(targetHost, targetReq);

        System.out.println("Request: " + targetHost + targetUrl + ", user " + user + " -> "
                + (System.currentTimeMillis() - time) + " msec: " + targetResp.getStatusLine());

        resp.setStatus(targetResp.getStatusLine().getStatusCode());
        targetResp.getEntity().writeTo(resp.getOutputStream());
    } catch (IOException | AuthenticationException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.android.unit_tests.TestHttpService.java

/**
 * This test case executes a series of simple GET requests 
 */// www . ja  va  2  s .  c  o m
@LargeTest
public void testSimpleBasicHttpRequests() throws Exception {

    int reqNo = 20;

    Random rnd = new Random();

    // Prepare some random data
    final List testData = new ArrayList(reqNo);
    for (int i = 0; i < reqNo; i++) {
        int size = rnd.nextInt(5000);
        byte[] data = new byte[size];
        rnd.nextBytes(data);
        testData.add(data);
    }

    // Initialize the server-side request handler
    this.server.registerHandler("*", new HttpRequestHandler() {

        public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {

            String s = request.getRequestLine().getUri();
            if (s.startsWith("/?")) {
                s = s.substring(2);
            }
            int index = Integer.parseInt(s);
            byte[] data = (byte[]) testData.get(index);
            ByteArrayEntity entity = new ByteArrayEntity(data);
            response.setEntity(entity);
        }

    });

    this.server.start();

    DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
    HttpHost host = new HttpHost("localhost", this.server.getPort());

    try {
        for (int r = 0; r < reqNo; r++) {
            if (!conn.isOpen()) {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket, this.client.getParams());
            }

            BasicHttpRequest get = new BasicHttpRequest("GET", "/?" + r);
            HttpResponse response = this.client.execute(get, host, conn);
            byte[] received = EntityUtils.toByteArray(response.getEntity());
            byte[] expected = (byte[]) testData.get(r);

            assertEquals(expected.length, received.length);
            for (int i = 0; i < expected.length; i++) {
                assertEquals(expected[i], received[i]);
            }
            if (!this.client.keepAlive(response)) {
                conn.close();
            }
        }

        //Verify the connection metrics
        HttpConnectionMetrics cm = conn.getMetrics();
        assertEquals(reqNo, cm.getRequestCount());
        assertEquals(reqNo, cm.getResponseCount());

    } finally {
        conn.close();
        this.server.shutdown();
    }
}

From source file:io.mapzone.controller.um.launcher.JvmProjectLauncher.java

protected void pollHttp(ProjectInstanceRecord instance) throws ClientProtocolException, IOException {
    log.info("SLEEP 1s: allow instance to start up...");
    try {/*from  w  w  w  .j  a  va  2  s. c  o  m*/
        Thread.sleep(1000);
    } catch (InterruptedException e) {
    }

    try (CloseableHttpClient httpClient = new SystemDefaultHttpClient();) {
        // XXX use Project#servletAlias
        BasicHttpRequest request = new BasicHttpRequest("GET", Project.DEFAULT_SERVLET_ALIAS);
        HttpHost host = new HttpHost(instance.host.get().inetAddress.get(), instance.process.get().port.get());

        // max 40x250ms => 10s
        for (int i = 0; i < 80; i++) {
            try (CloseableHttpResponse response = httpClient.execute(host, request);) {
                log.info(request.getRequestLine().getUri() + " -> " + response.getStatusLine().getStatusCode());
                if (response.getStatusLine().getStatusCode() == 200) {
                    return;
                }
            } catch (IOException e) {
                log.info("    response: " + e);
            }
            try {
                Thread.sleep(250);
            } catch (InterruptedException e) {
            }
        }
    }
}

From source file:ste.web.http.velocity.BugFreeVelocityHandler.java

@Test
public void viewInSubDirs() throws Exception {
    handler.setViewsFolder("/views");

    context.setAttribute(ATTR_VIEW, TEST_VIEW5);
    handler.handle(new BasicHttpRequest("GET", "/first/controller.bsh"), response, context);
    then(response.getStatusLine().getStatusCode()).isEqualTo(HttpStatus.SC_OK);
}

From source file:gr.wavesoft.webng.io.web.WebStreams.java

public static HttpResponse httpGET(URL url, HashMap<String, String> headers) throws IOException {
    try {/*from  www.  j  a v  a 2 s.c  om*/

        // WebRequest connection
        ClientConnectionRequest connRequest = connectionManager.requestConnection(
                new HttpRoute(new HttpHost(url.getHost(), url.getPort(), url.getProtocol())), null);

        ManagedClientConnection conn = connRequest.getConnection(10, TimeUnit.SECONDS);
        try {

            // Prepare request
            BasicHttpRequest request = new BasicHttpRequest("GET", url.getPath());

            // Setup headers
            if (headers != null) {
                for (String k : headers.keySet()) {
                    request.addHeader(k, headers.get(k));
                }
            }

            // Send request
            conn.sendRequestHeader(request);

            // Fetch response
            HttpResponse response = conn.receiveResponseHeader();
            conn.receiveResponseEntity(response);

            HttpEntity entity = response.getEntity();
            if (entity != null) {
                BasicManagedEntity managedEntity = new BasicManagedEntity(entity, conn, true);
                // Replace entity
                response.setEntity(managedEntity);
            }

            // Do something useful with the response
            // The connection will be released automatically 
            // as soon as the response content has been consumed
            return response;

        } catch (IOException ex) {
            // Abort connection upon an I/O error.
            conn.abortConnection();
            throw ex;
        }

    } catch (HttpException ex) {
        throw new IOException("HTTP Exception occured", ex);
    } catch (InterruptedException ex) {
        throw new IOException("InterruptedException", ex);
    } catch (ConnectionPoolTimeoutException ex) {
        throw new IOException("ConnectionPoolTimeoutException", ex);
    }

}

From source file:name.persistent.behaviours.RemoteGraphSupport.java

@Override
public boolean reload(String origin) throws Exception {
    String url = getResource().stringValue();
    BasicHttpRequest req = new BasicHttpRequest("GET", url);
    String type = getPurlContentType();
    if (type == null) {
        req.setHeader("Accept", "application/rdf+xml");
    } else {//w  w  w  .java2  s . c o  m
        req.setHeader("Accept", type);
    }
    String etag = getPurlEtag();
    if (etag != null) {
        req.setHeader("If-None-Match", etag);
    }
    XMLGregorianCalendar modified = getPurlLastModified();
    if (modified != null) {
        Date date = modified.toGregorianCalendar().getTime();
        req.setHeader("If-Modified-Since", DateUtil.formatDate(date));
    }
    HttpResponse resp = requestRDF(req, 20);
    int code = resp.getStatusLine().getStatusCode();
    if (code == 304) {
        DatatypeFactory df = DatatypeFactory.newInstance();
        GregorianCalendar gc = new GregorianCalendar();
        setPurlLastValidated(df.newXMLGregorianCalendar(gc));
        setPurlCacheControl(getHeader(resp, "Cache-Control"));
    }
    if (code == 304 || code == 404) {
        HttpEntity entity = resp.getEntity();
        if (entity != null) {
            entity.consumeContent();
        }
        return true;
    }
    return importResponse(resp, origin);
}

From source file:securitydigest.TestDigestScheme.java

public void testDigestAuthenticationWithSHA() throws Exception {
    String challenge = "Digest realm=\"realm1\", " + "nonce=\"f2a3f18799759d4f1a1c068b92b573cb\", "
            + "algorithm=SHA";
    Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge);
    HttpRequest request = new BasicHttpRequest("Simple", "/");
    Credentials cred = new UsernamePasswordCredentials("username", "password");
    AuthScheme authscheme = new DigestScheme();
    authscheme.processChallenge(authChallenge);
    Header authResponse = authscheme.authenticate(cred, request);

    Map<String, String> table = parseAuthResponse(authResponse);
    assertEquals("username", table.get("username"));
    assertEquals("realm1", table.get("realm"));
    assertEquals("/", table.get("uri"));
    assertEquals("f2a3f18799759d4f1a1c068b92b573cb", table.get("nonce"));
    assertEquals("8769e82e4e28ecc040b969562b9050580c6d186d", table.get("response"));
}

From source file:cn.knet.showcase.demos.servletproxy.ProxyServlet.java

protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {
    //initialize request attributes from caches if unset by a subclass by this point
    if (servletRequest.getAttribute(ATTR_TARGET_URI) == null) {
        servletRequest.setAttribute(ATTR_TARGET_URI, targetUri);
    }//from   w ww.j a v a  2 s . c o  m
    if (servletRequest.getAttribute(ATTR_TARGET_HOST) == null) {
        servletRequest.setAttribute(ATTR_TARGET_HOST, targetHost);
    }

    // Make the Request
    //note: we won't transfer the protocol version because I'm not sure it would truly be compatible
    String method = servletRequest.getMethod();
    String proxyRequestUri = rewriteUrlFromRequest(servletRequest);
    HttpRequest proxyRequest;
    //spec: RFC 2616, sec 4.3: either of these two headers signal that there is a message body.
    if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null
            || servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) {
        proxyRequest = newProxyRequestWithEntity(method, proxyRequestUri, servletRequest);
    } else {
        proxyRequest = new BasicHttpRequest(method, proxyRequestUri);
    }

    copyRequestHeaders(servletRequest, proxyRequest);

    setXForwardedForHeader(servletRequest, proxyRequest);

    HttpResponse proxyResponse = null;
    try {
        // Execute the request

        //Fallback on using older client:

        proxyResponse = proxyClient.execute(getTargetHost(servletRequest), proxyRequest);

        // Process the response:

        // Pass the response code. This method with the "reason phrase" is deprecated but it's the
        //   only way to pass the reason along too.
        int statusCode = proxyResponse.getStatusLine().getStatusCode();
        //noinspection deprecation
        servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase());

        // Copying response headers to make sure SESSIONID or other Cookie which comes from the remote
        // server will be saved in client when the proxied url was redirected to another one.
        // See issue [#51](https://github.com/mitre/HTTP-Proxy-Servlet/issues/51)
        copyResponseHeaders(proxyResponse, servletRequest, servletResponse);

        if (statusCode == HttpServletResponse.SC_NOT_MODIFIED) {
            // 304 needs special handling.  See:
            // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
            // Don't send body entity/content!
            servletResponse.setIntHeader(HttpHeaders.CONTENT_LENGTH, 0);
        } else {
            // Send the content to the client
            copyResponseEntity(proxyResponse, servletResponse);
        }

    } catch (Exception e) {
        //abort request, according to best practice with HttpClient
        if (proxyRequest instanceof AbortableHttpRequest) {
            AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest;
            abortableHttpRequest.abort();
        }
        if (e instanceof RuntimeException)
            throw (RuntimeException) e;
        if (e instanceof ServletException)
            throw (ServletException) e;
        //noinspection ConstantConditions
        if (e instanceof IOException)
            throw (IOException) e;
        throw new RuntimeException(e);

    } finally {
        // make sure the entire entity was consumed, so the connection is released
        if (proxyResponse != null)
            consumeQuietly(proxyResponse.getEntity());
        //Note: Don't need to close servlet outputStream:
        // http://stackoverflow.com/questions/1159168/should-one-call-close-on-httpservletresponse-getoutputstream-getwriter
    }
}

From source file:org.prx.prp.StreamProxy.java

private HttpRequest readRequest(Socket client) {
    HttpRequest request = null;//ww w .  j  av a2s  . co m
    InputStream is;
    String firstLine;
    try {
        is = client.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        firstLine = reader.readLine();
    } catch (IOException e) {
        Log.e(getClass().getName(), "Error parsing request", e);
        return request;
    }

    StringTokenizer st = new StringTokenizer(firstLine);
    String method = st.nextToken();
    String uri = st.nextToken();
    Log.d(getClass().getName(), uri);
    String realUri = uri.substring(1);
    Log.d(getClass().getName(), realUri);
    request = new BasicHttpRequest(method, realUri);
    return request;
}

From source file:com.ebay.spine.WindowsWebDriverVNCProxy.java

@Override
public boolean isAlive() {
    String url = getRemoteURL().toExternalForm() + "/status";
    BasicHttpRequest r = new BasicHttpRequest("GET", url);
    DefaultHttpClient client = new DefaultHttpClient();
    HttpHost host = new HttpHost(getRemoteURL().getHost(), getRemoteURL().getPort());
    HttpResponse response;//  www  .j ava  2s . c  o m
    try {
        response = client.execute(host, r);
    } catch (ClientProtocolException e) {
        return false;
    } catch (IOException e) {
        return false;
    }
    int code = response.getStatusLine().getStatusCode();
    return code == 200;
}