Example usage for org.apache.commons.httpclient HttpMethodBase getResponseBodyAsStream

List of usage examples for org.apache.commons.httpclient HttpMethodBase getResponseBodyAsStream

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethodBase getResponseBodyAsStream.

Prototype

@Override
public InputStream getResponseBodyAsStream() throws IOException 

Source Link

Document

Returns the response body of the HTTP method, if any, as an InputStream .

Usage

From source file:org.portletbridge.portlet.PortletBridgeServlet.java

/**
 * @param response/*from   ww w . j  a  v  a 2  s . com*/
 * @param bridgeRequest
 * @param perPortletMemento
 * @param url
 * @throws ServletException
 */
protected void fetch(final HttpServletRequest request, final HttpServletResponse response,
        final BridgeRequest bridgeRequest, final PortletBridgeMemento memento,
        final PerPortletMemento perPortletMemento, final URI url) throws ServletException {
    try {
        GetMethod getMethod = new GetMethod(url.toString());
        // TODO: suspect to send the same request headers after a redirect?
        copyRequestHeaders(request, getMethod);
        httpClientTemplate.service(getMethod, perPortletMemento, new HttpClientCallback() {
            public Object doInHttpClient(int statusCode, HttpMethodBase method)
                    throws ResourceException, Throwable {
                if (statusCode == HttpStatus.SC_OK) {
                    // if it's text/html then store it and redirect
                    // back to the portlet render view (portletUrl)
                    org.apache.commons.httpclient.URI effectiveUri = method.getURI();
                    BridgeRequest effectiveBridgeRequest = null;
                    if (!effectiveUri.toString().equals(url.toString())) {
                        PseudoRenderResponse renderResponse = createRenderResponse(bridgeRequest);
                        effectiveBridgeRequest = memento.createBridgeRequest(renderResponse,
                                new DefaultIdGenerator().nextId(), new URI(effectiveUri.toString()));
                    } else {
                        effectiveBridgeRequest = bridgeRequest;
                    }
                    Header responseHeader = method.getResponseHeader("Content-Type");
                    if (responseHeader != null && responseHeader.getValue().startsWith("text/html")) {
                        String content = ResourceUtil.getString(method.getResponseBodyAsStream(),
                                method.getResponseCharSet());
                        // TODO: think about cleaning this up if we
                        // don't get back to the render
                        perPortletMemento.enqueueContent(effectiveBridgeRequest.getId(),
                                new PortletBridgeContent(url, "get", content));
                        // redirect
                        // TODO: worry about this... adding the id
                        // at the end
                        response.sendRedirect(effectiveBridgeRequest.getPageUrl());
                    } else if (responseHeader != null
                            && responseHeader.getValue().startsWith("text/javascript")) {
                        // rewrite external javascript
                        String content = ResourceUtil.getString(method.getResponseBodyAsStream(),
                                method.getResponseCharSet());
                        BridgeFunctions bridge = bridgeFunctionsFactory.createBridgeFunctions(memento,
                                perPortletMemento, getServletName(), url,
                                new PseudoRenderRequest(request.getContextPath()),
                                createRenderResponse(effectiveBridgeRequest));
                        response.setContentType("text/javascript");
                        PrintWriter writer = response.getWriter();
                        writer.write(bridge.script(null, content));
                        writer.flush();
                    } else if (responseHeader != null && responseHeader.getValue().startsWith("text/css")) {
                        // rewrite external css
                        String content = ResourceUtil.getString(method.getResponseBodyAsStream(),
                                method.getResponseCharSet());
                        BridgeFunctions bridge = bridgeFunctionsFactory.createBridgeFunctions(memento,
                                perPortletMemento, getServletName(), url,
                                new PseudoRenderRequest(request.getContextPath()),
                                createRenderResponse(effectiveBridgeRequest));
                        response.setContentType("text/css");
                        PrintWriter writer = response.getWriter();
                        writer.write(bridge.style(null, content));
                        writer.flush();
                    } else {
                        // if it's anything else then stream it
                        // back... consider stylesheets and
                        // javascript
                        // TODO: javascript and css rewriting
                        Header header = method.getResponseHeader("Content-Type");
                        response.setContentType(((null == header.getName() ? "" : header.getName()) + ": "
                                + (null == header.getValue() ? "" : header.getValue())));

                        log.trace("fetch(): returning URL=" + url + ", as stream, content type=" + header);
                        ResourceUtil.copy(method.getResponseBodyAsStream(), response.getOutputStream(), 4096);
                    }
                } else {
                    // if there is a problem with the status code
                    // then return that error back
                    response.sendError(statusCode);
                }
                return null;
            }
        });
    } catch (ResourceException resourceException) {
        String format = MessageFormat.format(resourceBundle.getString(resourceException.getMessage()),
                resourceException.getArgs());
        throw new ServletException(format, resourceException);
    }
}

From source file:org.portletbridge.portlet.PortletBridgeServlet.java

protected void doPost(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    // get the id
    final String id = portletBridgeService.getIdFromRequestUri(request.getContextPath(),
            request.getRequestURI());// w  ww  . j ava 2 s  .  c  o m
    // look up the data associated with that id from the session
    HttpSession session = request.getSession();
    if (session == null) {
        throw new ServletException(resourceBundle.getString("error.nosession"));
    }
    final PortletBridgeMemento memento = (PortletBridgeMemento) session.getAttribute(mementoSessionKey);
    if (memento == null) {
        throw new ServletException(resourceBundle.getString("error.nomemento"));
    }
    final BridgeRequest bridgeRequest = memento.getBridgeRequest(id);
    if (bridgeRequest == null) {
        throw new ServletException(resourceBundle.getString("error.nobridgerequest"));
    }
    final PerPortletMemento perPortletMemento = memento.getPerPortletMemento(bridgeRequest.getPortletId());
    if (perPortletMemento == null) {
        throw new ServletException(resourceBundle.getString("error.noperportletmemento"));
    }

    // go and fetch the data from the backend as appropriate
    final URI url = bridgeRequest.getUrl();

    log.debug("doPost(): URL=" + url);

    try {
        PostMethod postMethod = new PostMethod(url.toString());
        copyRequestHeaders(request, postMethod);
        postMethod.setRequestEntity(new InputStreamRequestEntity(request.getInputStream()));
        httpClientTemplate.service(postMethod, perPortletMemento, new HttpClientCallback() {
            public Object doInHttpClient(int statusCode, HttpMethodBase method)
                    throws ResourceException, Throwable {
                if (statusCode == HttpStatus.SC_OK) {
                    // if it's text/html then store it and redirect
                    // back to the portlet render view (portletUrl)
                    Header responseHeader = method.getResponseHeader("Content-Type");
                    if (responseHeader != null && responseHeader.getValue().startsWith("text/html")) {
                        String content = ResourceUtil.getString(method.getResponseBodyAsStream(),
                                method.getResponseCharSet());
                        // TODO: think about cleaning this up if we
                        // don't get back to the render
                        perPortletMemento.enqueueContent(bridgeRequest.getId(),
                                new PortletBridgeContent(url, "post", content));
                        // redirect
                        // TODO: worry about this... adding the id
                        // at the end

                        log.debug("doPost(): doing response.sendRedirect to URL=" + bridgeRequest.getPageUrl());

                        response.sendRedirect(bridgeRequest.getPageUrl());
                    } else {
                        // if it's anything else then stream it
                        // back... consider stylesheets and
                        // javascript
                        // TODO: javascript and css rewriting
                        response.setContentType(method.getResponseHeader("Content-Type").toExternalForm());
                        ResourceUtil.copy(method.getResponseBodyAsStream(), response.getOutputStream(), 4096);
                    }
                } else if (statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                    Header locationHeader = method.getResponseHeader("Location");
                    if (locationHeader != null) {
                        URI redirectUrl = new URI(locationHeader.getValue().trim());
                        log.debug("redirecting to [" + redirectUrl + "]");
                        PseudoRenderResponse renderResponse = createRenderResponse(bridgeRequest);
                        BridgeRequest updatedBridgeRequest = memento.createBridgeRequest(renderResponse,
                                new DefaultIdGenerator().nextId(), redirectUrl);
                        fetch(request, response, updatedBridgeRequest, memento, perPortletMemento, redirectUrl);

                    } else {
                        throw new PortletBridgeException("error.missingLocation");
                    }
                } else {
                    // if there is a problem with the status code
                    // then return that error back
                    response.sendError(statusCode);
                }
                return null;
            }
        });
    } catch (ResourceException resourceException) {
        String format = MessageFormat.format(resourceBundle.getString(resourceException.getMessage()),
                resourceException.getArgs());
        throw new ServletException(format, resourceException);
    }
}

From source file:org.rhq.enterprise.server.plugins.url.HttpProvider.java

/**
 * Given any URL, will return a stream to that URL using the HTTP client and GET method
 * for the authentication as defined in this content source's configuration.
 * /*from  w ww  .j  a v  a2 s  . c  o  m*/
 * @param url the URL whose stream of content is returned
 *
 * @return stream containing the content for the given URL
 *
 * @throws Exception if cannot get the streamed content
 */
protected InputStream getInputStreamForUrl(URL url) throws Exception {
    String fullLocation = url.toString();

    HttpClient client = new HttpClient();
    HttpMethodBase method = new GetMethod(fullLocation);
    prepareHttpClient(client, method);
    int status = client.executeMethod(method);

    switch (status) {
    case HttpStatus.SC_OK: {
        break; // good to go
    }

    case HttpStatus.SC_NOT_FOUND: {
        throw new Exception("Could not find the content at URL [" + fullLocation
                + "]. Make sure the content source defines a valid URL.");
    }

    case HttpStatus.SC_UNAUTHORIZED:
    case HttpStatus.SC_FORBIDDEN: {
        throw new Exception("Invalid login credentials specified for user [" + username + "]. Make sure "
                + "this user is valid and the password specified for this content source is correct.");
    }

    default: {
        throw new Exception("Failed to retrieve content. status code=" + status);
    }
    }

    InputStream stream = method.getResponseBodyAsStream();

    return stream;
}

From source file:org.rssowl.core.internal.connection.DefaultProtocolHandler.java

private InputStream openConnection(HttpClient client, HttpMethodBase method) throws HttpException, IOException {

    /* Execute the Method */
    client.executeMethod(method);/*from  w  w  w .j  a  v  a2 s .  com*/

    /* Finally retrieve the InputStream from the respond body */
    return method.getResponseBodyAsStream();
}

From source file:org.sakaiproject.kernel.mailman.impl.MailmanManagerImpl.java

private Document parseHtml(HttpMethodBase method) throws SAXException, IOException {
    DOMParser parser = new DOMParser();
    parser.parse(new InputSource(method.getResponseBodyAsStream()));
    return parser.getDocument();
}

From source file:org.springfield.mojo.http.HttpHelper.java

/**
 * Sends a standard HTTP request to the specified URI using the determined method.
 * Attaches the content, uses the specified content type, sets cookies, timeout and
 * request headers//from w  ww  .  ja va  2 s .  c o  m
 *  
 * @param method - the request method
 * @param uri - the uri to request
 * @param body - the content  
 * @param contentType - the content type
 * @param cookies - cookies
 * @param timeout - timeout in milliseconds
 * @param charSet - the character set
 * @param requestHeaders - extra user defined headers
 * @return response
 */
public static Response sendRequest(String method, String uri, String body, String contentType, String cookies,
        int timeout, String charSet, Map<String, String> requestHeaders) {
    // http client
    HttpClient client = new HttpClient();

    // method
    HttpMethodBase reqMethod = null;
    if (method.equals(HttpMethods.PUT)) {
        reqMethod = new PutMethod(uri);
    } else if (method.equals(HttpMethods.POST)) {
        reqMethod = new PostMethod(uri);
    } else if (method.equals(HttpMethods.GET)) {
        if (body != null) {
            // hack to be able to send a request body with a get (only if required)
            reqMethod = new PostMethod(uri) {
                public String getName() {
                    return "GET";
                }
            };
        } else {
            reqMethod = new GetMethod(uri);
        }
    } else if (method.equals(HttpMethods.DELETE)) {
        if (body != null) {
            // hack to be able to send a request body with a delete (only if required)
            reqMethod = new PostMethod(uri) {
                public String getName() {
                    return "DELETE";
                }
            };
        } else {
            reqMethod = new DeleteMethod(uri);
        }
    } else if (method.equals(HttpMethods.HEAD)) {
        reqMethod = new HeadMethod(uri);
    } else if (method.equals(HttpMethods.TRACE)) {
        reqMethod = new TraceMethod(uri);
    } else if (method.equals(HttpMethods.OPTIONS)) {
        reqMethod = new OptionsMethod(uri);
    }

    // add request body
    if (body != null) {
        try {
            RequestEntity entity = new StringRequestEntity(body, contentType, charSet);
            ((EntityEnclosingMethod) reqMethod).setRequestEntity(entity);
            reqMethod.setRequestHeader("Content-type", contentType);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // add cookies
    if (cookies != null) {
        reqMethod.addRequestHeader("Cookie", cookies);
    }

    // add custom headers
    if (requestHeaders != null) {
        for (Map.Entry<String, String> header : requestHeaders.entrySet()) {
            String name = header.getKey();
            String value = header.getValue();

            reqMethod.addRequestHeader(name, value);
        }
    }

    Response response = new Response();

    // do request
    try {
        if (timeout != -1) {
            client.getParams().setSoTimeout(timeout);
        }
        int statusCode = client.executeMethod(reqMethod);
        response.setStatusCode(statusCode);
    } catch (Exception e) {
        e.printStackTrace();
    }

    // read response
    try {
        InputStream instream = reqMethod.getResponseBodyAsStream();
        ByteArrayOutputStream outstream = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int len;
        while ((len = instream.read(buffer)) > 0) {
            outstream.write(buffer, 0, len);
        }
        String resp = new String(outstream.toByteArray(), reqMethod.getResponseCharSet());
        response.setResponse(resp);

        //set content length
        long contentLength = reqMethod.getResponseContentLength();
        response.setContentLength(contentLength);
        //set character set
        String respCharSet = reqMethod.getResponseCharSet();
        response.setCharSet(respCharSet);
        //set all headers
        Header[] headers = reqMethod.getResponseHeaders();
        response.setHeaders(headers);
    } catch (Exception e) {
        e.printStackTrace();
    }

    // release connection
    reqMethod.releaseConnection();

    // return
    return response;
}

From source file:smartrics.jmeter.sampler.RestSampler.java

/**
 * Method invoked by JMeter when a sample needs to happen. It's actually an
 * indirect call from the main sampler interface. it's resolved in the base
 * class.//www .ja v  a 2s  .c  om
 * 
 * This is a copy and paste from the HTTPSampler2 - quick and dirty hack as
 * that class is not very extensible. The reason to extend and slightly
 * modify is that I needed to get the body content from a text field in the
 * GUI rather than a file.
 */
protected HTTPSampleResult sample(URL url, String method, boolean areFollowingRedirect, int frameDepth) {

    String urlStr = url.toString();

    log.debug("Start : sample " + urlStr);
    log.debug("method " + method);

    HttpMethodBase httpMethod = null;

    HTTPSampleResult res = new HTTPSampleResult();
    res.setMonitor(isMonitor());

    res.setSampleLabel(urlStr); // May be replaced later
    res.setHTTPMethod(method);
    res.setURL(url);
    res.sampleStart(); // Count the retries as well in the time
    HttpClient client = null;
    InputStream instream = null;
    try {
        httpMethod = createHttpMethod(method, urlStr);
        // Set any default request headers
        res.setRequestHeaders("");
        // Setup connection
        client = setupConnection(url, httpMethod, res);
        // Handle the various methods
        if (httpMethod instanceof EntityEnclosingMethod) {
            String postBody = sendData((EntityEnclosingMethod) httpMethod);
            res.setResponseData(postBody.getBytes());
        }
        overrideHeaders(httpMethod);
        res.setRequestHeaders(getConnectionHeaders(httpMethod));

        int statusCode = -1;
        try {
            statusCode = client.executeMethod(httpMethod);
        } catch (RuntimeException e) {
            log.error("Exception when executing '" + httpMethod + "'", e);
            throw e;
        }

        // Request sent. Now get the response:
        instream = httpMethod.getResponseBodyAsStream();

        if (instream != null) {// will be null for HEAD

            Header responseHeader = httpMethod.getResponseHeader(HEADER_CONTENT_ENCODING);
            if (responseHeader != null && ENCODING_GZIP.equals(responseHeader.getValue())) {
                instream = new GZIPInputStream(instream);
            }
            res.setResponseData(readResponse(res, instream, (int) httpMethod.getResponseContentLength()));
        }

        res.sampleEnd();
        // Done with the sampling proper.

        // Now collect the results into the HTTPSampleResult:

        res.setSampleLabel(httpMethod.getURI().toString());
        // Pick up Actual path (after redirects)

        res.setResponseCode(Integer.toString(statusCode));
        res.setSuccessful(isSuccessCode(statusCode));

        res.setResponseMessage(httpMethod.getStatusText());

        String ct = null;
        org.apache.commons.httpclient.Header h = httpMethod.getResponseHeader(HEADER_CONTENT_TYPE);
        if (h != null)// Can be missing, e.g. on redirect
        {
            ct = h.getValue();
            res.setContentType(ct);// e.g. text/html; charset=ISO-8859-1
            res.setEncodingAndType(ct);
        }

        String responseHeaders = getResponseHeaders(httpMethod);
        res.setResponseHeaders(responseHeaders);
        if (res.isRedirect()) {
            final Header headerLocation = httpMethod.getResponseHeader(HEADER_LOCATION);
            if (headerLocation == null) { // HTTP protocol violation, but
                // avoids NPE
                throw new IllegalArgumentException("Missing location header");
            }
            res.setRedirectLocation(headerLocation.getValue());
        }

        // If we redirected automatically, the URL may have changed
        if (getAutoRedirects()) {
            res.setURL(new URL(httpMethod.getURI().toString()));
        }

        // Store any cookies received in the cookie manager:
        saveConnectionCookies(httpMethod, res.getURL(), getCookieManager());

        // Save cache information
        final CacheManager cacheManager = getCacheManager();
        if (cacheManager != null) {
            cacheManager.saveDetails(httpMethod, res);
        }

        // Follow redirects and download page resources if appropriate:
        res = resultProcessing(areFollowingRedirect, frameDepth, res);

        log.debug("End : sample");
        httpMethod.releaseConnection();
        return res;
    } catch (IllegalArgumentException e)// e.g. some kinds of invalid URL
    {
        res.sampleEnd();
        HTTPSampleResult err = errorResult(e, res);
        err.setSampleLabel("Error: " + url.toString());
        return err;
    } catch (IOException e) {
        res.sampleEnd();
        HTTPSampleResult err = errorResult(e, res);
        err.setSampleLabel("Error: " + url.toString());
        return err;
    } finally {
        JOrphanUtils.closeQuietly(instream);
        if (httpMethod != null) {
            httpMethod.releaseConnection();
        }
    }
}