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

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

Introduction

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

Prototype

HttpRequestBase

Source Link

Usage

From source file:io.undertow.server.InvalidHtpRequestTestCase.java

@Test
public void testInvalidCharacterInMethod() throws IOException {
    final TestHttpClient client = new TestHttpClient();
    try {/*from  w  w w . ja v a 2s  .co m*/
        HttpRequestBase method = new HttpRequestBase() {

            @Override
            public String getMethod() {
                return "GET;POST";
            }

            @Override
            public URI getURI() {
                try {
                    return new URI(DefaultServer.getDefaultServerURL());
                } catch (URISyntaxException e) {
                    throw new RuntimeException(e);
                }
            }
        };
        HttpResponse result = client.execute(method);
        Assert.assertEquals(StatusCodes.BAD_REQUEST, result.getStatusLine().getStatusCode());
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:com.web.server.ProxyServlet.java

@Override
@SuppressWarnings("unchecked")
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // Create new client to perform the proxied request
    HttpClient httpclient = new DefaultHttpClient();

    // Determine final URL
    StringBuffer uri = new StringBuffer();
    uri.append(targetServer);//from  w  ww.  j  a v a  2s .co m
    uri.append(req.getRequestURI());

    // Add any supplied query strings
    String queryString = req.getQueryString();
    if (queryString != null) {
        uri.append("?" + queryString);
    }

    // Get HTTP method
    final String method = req.getMethod();
    // Create new HTTP request container
    HttpRequestBase request = null;

    // Get content length
    int contentLength = req.getContentLength();
    // Unknown content length ...
    //       if (contentLength == -1)
    //          throw new ServletException("Cannot handle unknown content length");
    // If we don't have an entity body, things are quite simple
    if (contentLength < 1) {
        request = new HttpRequestBase() {
            public String getMethod() {
                return method;
            }
        };
    } else {
        // Prepare request
        HttpEntityEnclosingRequestBase tmpRequest = new HttpEntityEnclosingRequestBase() {
            public String getMethod() {
                return method;
            }
        };

        // Transfer entity body from the received request to the new request
        InputStreamEntity entity = new InputStreamEntity(req.getInputStream(), contentLength);
        tmpRequest.setEntity(entity);

        request = tmpRequest;
    }

    // Set URI
    try {
        request.setURI(new URI(uri.toString()));
    } catch (URISyntaxException e) {
        throw new ServletException("URISyntaxException: " + e.getMessage());
    }

    // Copy headers from old request to new request
    // @todo not sure how this handles multiple headers with the same name
    Enumeration<String> headers = req.getHeaderNames();
    while (headers.hasMoreElements()) {
        String headerName = headers.nextElement();
        String headerValue = req.getHeader(headerName);
        // Skip Content-Length and Host
        String lowerHeader = headerName.toLowerCase();
        if (lowerHeader.equals("content-length") == false && lowerHeader.equals("host") == false) {
            //             System.out.println(headerName.toLowerCase() + ": " + headerValue);
            request.addHeader(headerName, headerValue);
        }
    }

    // Execute the request
    HttpResponse response = httpclient.execute(request);

    // Transfer status code to the response
    StatusLine status = response.getStatusLine();
    resp.setStatus(status.getStatusCode());
    // resp.setStatus(status.getStatusCode(), status.getReasonPhrase()); // This seems to be deprecated. Yes status message is "ambigous", but I don't approve

    // Transfer headers to the response
    Header[] responseHeaders = response.getAllHeaders();
    for (int i = 0; i < responseHeaders.length; i++) {
        Header header = responseHeaders[i];
        resp.addHeader(header.getName(), header.getValue());
    }

    // Transfer proxy response entity to the servlet response
    HttpEntity entity = response.getEntity();
    InputStream input = entity.getContent();
    OutputStream output = resp.getOutputStream();
    int b = input.read();
    while (b != -1) {
        output.write(b);
        b = input.read();
    }

    // Clean up
    input.close();
    output.close();
    httpclient.getConnectionManager().shutdown();
}

From source file:org.gnode.wda.server.ProxyServlet.java

License:asdf

@Override
@SuppressWarnings("unchecked")
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // Create new client to perform the proxied request
    HttpClient httpclient = new DefaultHttpClient();

    // Determine final URL
    StringBuffer uri = new StringBuffer();
    uri.append(targetServer);/*  w  w w.  j  ava2  s  .  c  om*/
    // This is a very bad hack. In order to remove my proxy servlet-path, I have used a substring method.
    // Turns "/proxy/asdf" into "/asdf"
    uri.append(req.getRequestURI().substring(6));

    //    Add any supplied query strings
    String queryString = req.getQueryString();
    if (queryString != null) {
        uri.append("?" + queryString);
    }

    // Get HTTP method
    final String method = req.getMethod();
    // Create new HTTP request container
    HttpRequestBase request = null;

    // Get content length
    int contentLength = req.getContentLength();
    //    Unknown content length ...
    // if (contentLength == -1)
    // throw new ServletException("Cannot handle unknown content length");
    // If we don't have an entity body, things are quite simple
    if (contentLength < 1) {
        request = new HttpRequestBase() {
            public String getMethod() {
                return method;
            }
        };
    } else {
        // Prepare request
        HttpEntityEnclosingRequestBase tmpRequest = new HttpEntityEnclosingRequestBase() {
            public String getMethod() {
                return method;
            }
        };

        // Transfer entity body from the received request to the new request
        InputStreamEntity entity = new InputStreamEntity(req.getInputStream(), contentLength);
        tmpRequest.setEntity(entity);

        request = tmpRequest;
    }

    //    Set URI
    try {
        request.setURI(new URI(uri.toString()));
    } catch (URISyntaxException e) {
        throw new ServletException("URISyntaxException: " + e.getMessage());
    }

    //       Copy headers from old request to new request
    // @todo not sure how this handles multiple headers with the same name
    Enumeration<String> headers = req.getHeaderNames();
    while (headers.hasMoreElements()) {
        String headerName = headers.nextElement();
        String headerValue = req.getHeader(headerName);
        //       Skip Content-Length and Host
        String lowerHeader = headerName.toLowerCase();
        if (lowerHeader.equals("content-length") == false && lowerHeader.equals("host") == false) {
            //    System.out.println(headerName.toLowerCase() + ": " + headerValue);
            request.addHeader(headerName, headerValue);
        }
    }

    // Execute the request
    HttpResponse response = httpclient.execute(request);

    // Transfer status code to the response
    StatusLine status = response.getStatusLine();
    resp.setStatus(status.getStatusCode());
    // resp.setStatus(status.getStatusCode(), status.getReasonPhrase()); // This seems to be deprecated. Yes status message is "ambigous", but I don't approve

    // Transfer headers to the response
    Header[] responseHeaders = response.getAllHeaders();
    for (int i = 0; i < responseHeaders.length; i++) {
        Header header = responseHeaders[i];
        resp.addHeader(header.getName(), header.getValue());
    }

    //    Transfer proxy response entity to the servlet response
    HttpEntity entity = response.getEntity();

    if (entity == null)
        return;

    InputStream input = entity.getContent();
    OutputStream output = resp.getOutputStream();
    int b = input.read();
    while (b != -1) {
        output.write(b);
        b = input.read();
    }

    //       Clean up
    input.close();
    output.close();
    httpclient.getConnectionManager().shutdown();
}

From source file:com.dp.bigdata.taurus.web.servlet.CreateTaskServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    HttpClient httpclient = new DefaultHttpClient();
    // Determine final URL
    StringBuffer uri = new StringBuffer();

    if (req.getParameter("update") != null) {
        uri.append(targetUri).append("/").append(req.getParameter("update"));
    } else {/* www  .  j  a v  a2  s .c  om*/
        uri.append(targetUri);
    }
    LOG.info("Access URI : " + uri.toString());
    // Get HTTP method
    final String method = req.getMethod();
    // Create new HTTP request container
    HttpRequestBase request = null;

    // Get content length
    int contentLength = req.getContentLength();
    // Unknown content length ...
    // if (contentLength == -1)
    // throw new ServletException("Cannot handle unknown content length");
    // If we don't have an entity body, things are quite simple
    if (contentLength < 1) {
        request = new HttpRequestBase() {
            public String getMethod() {
                return method;
            }
        };
    } else {
        // Prepare request
        HttpEntityEnclosingRequestBase tmpRequest = new HttpEntityEnclosingRequestBase() {
            public String getMethod() {
                return method;
            }
        };
        // Transfer entity body from the received request to the new request
        InputStreamEntity entity = new InputStreamEntity(req.getInputStream(), contentLength);
        tmpRequest.setEntity(entity);
        request = tmpRequest;
    }

    // Set URI
    try {
        request.setURI(new URI(uri.toString()));
    } catch (URISyntaxException e) {
        throw new ServletException("URISyntaxException: " + e.getMessage());
    }

    // Copy headers from old request to new request
    // @todo not sure how this handles multiple headers with the same name
    Enumeration<?> headers = req.getHeaderNames();
    while (headers.hasMoreElements()) {
        String headerName = (String) headers.nextElement();
        String headerValue = req.getHeader(headerName);
        //LOG.info("header: " + headerName + " value: " + headerValue);
        // Skip Content-Length and Host
        String lowerHeader = headerName.toLowerCase();
        if (lowerHeader.equals("content-type")) {
            request.addHeader(headerName, headerValue + ";charset=\"utf-8\"");
        } else if (!lowerHeader.equals("content-length") && !lowerHeader.equals("host")) {
            request.addHeader(headerName, headerValue);
        }
    }

    // Execute the request
    HttpResponse response = httpclient.execute(request);
    // Transfer status code to the response
    StatusLine status = response.getStatusLine();
    resp.setStatus(status.getStatusCode());

    // Transfer headers to the response
    Header[] responseHeaders = response.getAllHeaders();
    for (int i = 0; i < responseHeaders.length; i++) {
        Header header = responseHeaders[i];
        if (!header.getName().equals("Transfer-Encoding"))
            resp.addHeader(header.getName(), header.getValue());
    }

    // Transfer proxy response entity to the servlet response
    HttpEntity entity = response.getEntity();
    InputStream input = entity.getContent();
    OutputStream output = resp.getOutputStream();

    byte buffer[] = new byte[50];
    while (input.read(buffer) != -1) {
        output.write(buffer);
    }
    //        int b = input.read();
    //        while (b != -1) {
    //            output.write(b);
    //            b = input.read();
    //        }
    // Clean up
    input.close();
    output.close();
    httpclient.getConnectionManager().shutdown();
}

From source file:org.jclouds.http.apachehc.ApacheHCUtils.java

public HttpUriRequest convertToApacheRequest(HttpRequest request) {
    HttpUriRequest apacheRequest;//from   w  w  w .  java 2s .com
    if (request.getMethod().equals(HttpMethod.HEAD)) {
        apacheRequest = new HttpHead(request.getEndpoint());
    } else if (request.getMethod().equals(HttpMethod.GET)) {
        apacheRequest = new HttpGet(request.getEndpoint());
    } else if (request.getMethod().equals(HttpMethod.DELETE)) {
        apacheRequest = new HttpDelete(request.getEndpoint());
    } else if (request.getMethod().equals(HttpMethod.PUT)) {
        apacheRequest = new HttpPut(request.getEndpoint());
        apacheRequest.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true);
    } else if (request.getMethod().equals(HttpMethod.POST)) {
        apacheRequest = new HttpPost(request.getEndpoint());
    } else {
        final String method = request.getMethod();
        if (request.getPayload() != null)
            apacheRequest = new HttpEntityEnclosingRequestBase() {

                @Override
                public String getMethod() {
                    return method;
                }

            };
        else
            apacheRequest = new HttpRequestBase() {

                @Override
                public String getMethod() {
                    return method;
                }

            };
        HttpRequestBase.class.cast(apacheRequest).setURI(request.getEndpoint());
    }
    Payload payload = request.getPayload();

    // Since we may remove headers, ensure they are added to the apache
    // request after this block
    if (apacheRequest instanceof HttpEntityEnclosingRequest) {
        if (payload != null) {
            addEntityForContent(HttpEntityEnclosingRequest.class.cast(apacheRequest), payload);
        }
    } else {
        apacheRequest.addHeader(HttpHeaders.CONTENT_LENGTH, "0");
    }

    for (Map.Entry<String, String> entry : request.getHeaders().entries()) {
        String header = entry.getKey();
        // apache automatically tries to add content length header
        if (!header.equals(HttpHeaders.CONTENT_LENGTH))
            apacheRequest.addHeader(header, entry.getValue());
    }
    apacheRequest.addHeader(HttpHeaders.USER_AGENT, USER_AGENT);
    return apacheRequest;
}

From source file:org.apache.juneau.rest.client.RestClient.java

/**
 * Perform a generic REST call./* www  . j  ava 2s  .  co m*/
 *
 * @param method The method name (e.g. <js>"GET"</js>, <js>"OPTIONS"</js>).
 * @param url The URL of the remote REST resource.  Can be any of the following:  {@link String}, {@link URI}, {@link URL}.
 * @param hasContent Boolean flag indicating if the specified request has content associated with it.
 * @return A {@link RestCall} object that can be further tailored before executing the request
 *    and getting the response as a parsed object.
 * @throws RestCallException If any authentication errors occurred.
 */
public RestCall doCall(String method, Object url, boolean hasContent) throws RestCallException {
    if (isClosed) {
        Exception e2 = null;
        if (closedStack != null) {
            e2 = new Exception("Creation stack:");
            e2.setStackTrace(closedStack);
            throw new RestCallException(
                    "RestClient.close() has already been called.  This client cannot be reused.").initCause(e2);
        }
        throw new RestCallException(
                "RestClient.close() has already been called.  This client cannot be reused.  Closed location stack trace can be displayed by setting the system property 'org.apache.juneau.rest.client.RestClient.trackCreation' to true.");
    }

    HttpRequestBase req = null;
    RestCall restCall = null;
    final String methodUC = method.toUpperCase(Locale.ENGLISH);
    try {
        if (hasContent) {
            req = new HttpEntityEnclosingRequestBase() {
                @Override /* HttpRequest */
                public String getMethod() {
                    return methodUC;
                }
            };
            restCall = new RestCall(this, req, toURI(url));
        } else {
            req = new HttpRequestBase() {
                @Override /* HttpRequest */
                public String getMethod() {
                    return methodUC;
                }
            };
            restCall = new RestCall(this, req, toURI(url));
        }
    } catch (URISyntaxException e1) {
        throw new RestCallException(e1);
    }
    for (Map.Entry<String, ? extends Object> e : headers.entrySet())
        restCall.header(e.getKey(), e.getValue());

    if (parser != null && !req.containsHeader("Accept"))
        req.setHeader("Accept", parser.getPrimaryMediaType().toString());

    return restCall;
}