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.entando.entando.plugins.jpoauthclient.aps.system.services.client.ProviderConnectionManager.java

private String invokeGetDeleteMethod(String url, boolean isGet, Properties parameters) throws Throwable {
    String result = null;//from   w w w .  j a  va  2 s .  c  om
    HttpMethodBase method = null;
    InputStream inputStream = null;
    try {
        HttpClient client = new HttpClient();
        if (isGet) {
            method = new GetMethod(url);
        } else {
            method = new DeleteMethod(url);
        }
        this.addQueryString(method, parameters);
        client.executeMethod(method);
        inputStream = method.getResponseBodyAsStream();
        result = IOUtils.toString(inputStream, "UTF-8");
        //byte[] responseBody = method.getResponseBody();
        //result = new String(responseBody);
    } catch (Throwable t) {
        _logger.error("Error invoking Get or Delete Method", t);
    } finally {
        if (null != inputStream) {
            inputStream.close();
        }
        if (null != method) {
            method.releaseConnection();
        }
    }
    return result;
}

From source file:org.fao.geonet.csw.common.requests.CatalogRequest.java

private Element doExecute(HttpMethodBase httpMethod) throws IOException, JDOMException {
    client.getHostConfiguration().setHost(host, port, protocol);

    byte[] data = null;

    try {/*from  w w  w. j a  va 2  s.c  o m*/
        client.executeMethod(httpMethod);

        ///data = httpMethod.getResponseBody();
        // If server return HTTP Error 500 Server error 
        // when retrieving the data return null
        if (httpMethod.getStatusCode() == 500) {
            System.out.println("  Status code: " + httpMethod.getStatusCode());
            return null;
        } else {
            return Xml.loadStream(httpMethod.getResponseBodyAsStream());
        }
    } finally {
        httpMethod.releaseConnection();
        try {
            setupSentData(httpMethod);
            setupReceivedData(httpMethod, data);
        } catch (Throwable e) {
            Log.warning(Geonet.HARVESTER,
                    "Exception was raised during cleanup of a CSW request : " + Util.getStackTrace(e));
        }
    }
}

From source file:org.folg.werelatedata.editor.PageEditor.java

private String getResponse(HttpMethodBase m) throws IOException {
    InputStream s = m.getResponseBodyAsStream();
    int bytesRead = -1;
    int totalBytes = 0;
    int bytesToRead = BUF_SIZE;
    byte[] buf = new byte[BUF_SIZE];
    while (true) {
        bytesRead = s.read(buf, totalBytes, bytesToRead);
        if (bytesRead < 0) {
            break;
        }/*  w  ww .  jav a  2  s .c  o  m*/
        totalBytes += bytesRead;
        bytesToRead -= bytesRead;
        if (bytesToRead == 0) { // buffer full, so allocate more
            if (buf.length * 2 > MAX_BUF_SIZE) {
                throw new IOException("Response too long: " + m.getURI().toString());
            }
            byte[] temp = buf;
            buf = new byte[temp.length * 2];
            System.arraycopy(temp, 0, buf, 0, temp.length);
            bytesToRead = temp.length;
        }
    }
    if (totalBytes > 0) {
        return EncodingUtil.getString(buf, 0, totalBytes, m.getResponseCharSet());
    } else {
        return null;
    }
}

From source file:org.httpobjects.proxy.Proxy.java

protected Response createResponse(final HttpMethodBase method, ResponseCode responseCode,
        List<HeaderField> headersReturned) {
    return new Response(responseCode, new Representation() {
        @Override/*from  ww  w  .j  a  v a 2s. com*/
        public String contentType() {
            Header h = method.getResponseHeader("Content-Type");
            return h == null ? null : h.getValue();
        }

        @Override
        public void write(OutputStream out) {
            try {
                if (method.getResponseBodyAsStream() != null) {

                    byte[] buffer = new byte[1024];
                    InputStream in = method.getResponseBodyAsStream();
                    for (int x = in.read(buffer); x != -1; x = in.read(buffer)) {
                        out.write(buffer, 0, x);
                    }
                }

            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException("Error writing response", e);
            }
        }
    }, headersReturned.toArray(new HeaderField[] {}));
}

From source file:org.jahia.modules.filter.WebClippingFilter.java

private String getResponse(String urlToClip, RenderContext renderContext, Resource resource, RenderChain chain,
        HttpMethodBase httpMethod, HttpClient httpClient) {
    try {//from  w  ww  . j  av  a 2  s  . com
        httpMethod.getParams().setParameter("http.connection.timeout",
                resource.getNode().getPropertyAsString("connectionTimeout"));
        httpMethod.getParams().setParameter("http.protocol.expect-continue",
                Boolean.valueOf(resource.getNode().getPropertyAsString("expectContinue")));
        httpMethod.getParams().setCookiePolicy(CookiePolicy.RFC_2965);

        int statusCode = httpClient.executeMethod(httpMethod);

        if (statusCode == HttpStatus.SC_MOVED_TEMPORARILY || statusCode == HttpStatus.SC_MOVED_PERMANENTLY
                || statusCode == HttpStatus.SC_SEE_OTHER || statusCode == HttpStatus.SC_TEMPORARY_REDIRECT) {
            if (log.isDebugEnabled()) {
                log.debug("We follow a redirection ");
            }
            String redirectLocation;
            Header locationHeader = httpMethod.getResponseHeader("location");
            if (locationHeader != null) {
                redirectLocation = locationHeader.getValue();
                if (!redirectLocation.startsWith("http")) {
                    URL siteURL = new URL(urlToClip);
                    String tmpURL = siteURL.getProtocol() + "://" + siteURL.getHost()
                            + ((siteURL.getPort() > 0) ? ":" + siteURL.getPort() : "") + "/" + redirectLocation;
                    httpMethod = new GetMethod(tmpURL);
                    // Set a default retry handler (see httpclient doc).
                    httpMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                            new DefaultHttpMethodRetryHandler(3, false));
                    httpMethod.getParams().setParameter("http.connection.timeout",
                            resource.getNode().getPropertyAsString("connectionTimeout"));
                    httpMethod.getParams().setParameter("http.protocol.expect-continue",
                            resource.getNode().getPropertyAsString("expectContinue"));
                    httpMethod.getParams().setCookiePolicy(CookiePolicy.RFC_2965);
                } else {
                    httpMethod = new GetMethod(redirectLocation);
                }
            }
        }
        if (statusCode != HttpStatus.SC_OK) {
            //this.cacheable = false;
            StringBuffer buffer = new StringBuffer("<html>\n<body>");
            buffer.append('\n' + "Error getting ").append(urlToClip).append(" failed with error code ")
                    .append(statusCode);
            buffer.append("\n</body>\n</html>");
            return buffer.toString();
        }

        String[] type = httpMethod.getResponseHeader("Content-Type").getValue().split(";");
        String contentCharset = "UTF-8";
        if (type.length == 2) {
            contentCharset = type[1].split("=")[1];
        }
        InputStream inputStream = new BufferedInputStream(httpMethod.getResponseBodyAsStream());
        if (inputStream != null) {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream(100 * 1024);
            byte[] buffer = new byte[100 * 1024];
            int len;
            while ((len = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, len);
            }
            outputStream.close();
            inputStream.close();
            final byte[] responseBodyAsBytes = outputStream.toByteArray();
            String responseBody = new String(responseBodyAsBytes, "US-ASCII");
            Source source = new Source(responseBody);
            List list = source.getAllStartTags(HTMLElementName.META);
            for (Object aList : list) {
                StartTag startTag = (StartTag) aList;
                Attributes attributes = startTag.getAttributes();
                final Attribute attribute = attributes.get("http-equiv");
                if (attribute != null && attribute.getValue().equalsIgnoreCase("content-type")) {
                    type = attributes.get("content").getValue().split(";");
                    if (type.length == 2) {
                        contentCharset = type[1].split("=")[1];
                    }
                }
            }
            final String s = contentCharset.toUpperCase();
            return rewriteBody(new String(responseBodyAsBytes, s), urlToClip, s, resource, renderContext);
        }
    } catch (Exception e) {
        e.printStackTrace();
        //this.cacheable = false;
        StringBuffer buffer = new StringBuffer("<html>\n<body>");
        buffer.append('\n' + "Error getting ").append(urlToClip).append(" failed with error : ")
                .append(e.toString());
        buffer.append("\n</body>\n</html>");
        return buffer.toString();
    }
    return null;
}

From source file:org.jboss.test.security.test.authorization.ACLIntegrationUnitTestCase.java

/**
 * <p>//  w  w  w.j av a 2 s  .c  om
 * Reads the response contents and create a {@code List<String>} where each component corresponds to one line of the
 * response body.
 * </p>
 * 
 * @param response the {@code HttpServletResponse} that contains the response from the {@code ACLServlet}.
 * @return a {@code List<String>}, where each element corresponds to one line of the response body.
 * @throws Exception
 */
private List<String> readEntitlementsFromResponse(HttpMethodBase response) throws Exception {
    BufferedReader reader = new BufferedReader(new InputStreamReader(response.getResponseBodyAsStream()));
    List<String> entitlements = new ArrayList<String>();
    String line = reader.readLine();
    while (line != null) {
        entitlements.add(line);
        line = reader.readLine();
    }
    return entitlements;
}

From source file:org.kuali.mobility.knowledgebase.service.KnowledgeBaseServiceImpl.java

private String callKnowledgeBase(String url, RequestEntity requestEntity, boolean isPost) throws Exception {
    String output = null;/*from   w ww  . java  2 s  . c  o m*/
    //      Document doc = null;
    //      SAXBuilder builder = new SAXBuilder();
    //      BufferedReader in = null;

    HttpClient client = null;
    client = new HttpClient();
    Credentials defaultcreds = new UsernamePasswordCredentials(this.username, this.password);
    client.getState().setCredentials(new AuthScope("remote.kb.iu.edu", 80, AuthScope.ANY_REALM), defaultcreds);
    HttpMethodBase method = null;
    if (isPost) {
        method = preparePostMethod(url, requestEntity);
    } else {
        method = new GetMethod(url);
    }
    method.setDoAuthentication(true);

    //      int timeout = getSocketTimeout(Constants.RSS_SOCKET_TIMEOUT_SECONDS, Constants.RSS_SOCKET_DEFAULT_TIMEOUT);
    int timeout = getSocketTimeout("blah", 5000);
    client.getParams().setParameter(HttpClientParams.SO_TIMEOUT, new Integer(timeout));
    client.getParams().setParameter(HttpClientParams.CONNECTION_MANAGER_TIMEOUT, new Long(timeout));
    client.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, new Integer(timeout));
    try {
        int status = client.executeMethod(method);
        //            System.out.println(status + "\n" + get.getResponseBodyAsString());
        //            in = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
        //            doc = builder.build(in);
        output = this.inputStreamToString(method.getResponseBodyAsStream());
    } finally {
        method.releaseConnection();
    }

    return output;
}

From source file:org.mskcc.cbio.portal.util.ResponseUtil.java

/**
 * Reads in the Response String from Server.
 *
 * @param method HTTP Method./* w w w  . j a v a 2s . co m*/
 * @return Response String.
 * @throws IOException IO Error.
 */
public static String getResponseString(HttpMethodBase method) throws IOException {
    return getResponseString(method.getResponseBodyAsStream());
}

From source file:org.openrdf.repository.sparql.query.SPARQLGraphQuery.java

public GraphQueryResult evaluate() throws QueryEvaluationException {
    try {/*from   ww w . j  a v  a  2  s  .c om*/
        BackgroundGraphResult result = null;
        HttpMethodBase response = getResponse();
        try {
            RDFParser parser = getParser(response);
            InputStream in = response.getResponseBodyAsStream();
            String charset_str = response.getResponseCharSet();
            Charset charset;
            try {
                charset = Charset.forName(charset_str);
            } catch (IllegalCharsetNameException e) {
                // work around for Joseki-3.2
                // Content-Type: application/rdf+xml;
                // charset=application/rdf+xml
                charset = Charset.forName("UTF-8");
            }
            result = new BackgroundGraphResult(parser, in, charset, getUrl(), response);
            execute(result);
            return result;
        } catch (HttpException e) {
            throw new QueryEvaluationException(e);
        } finally {
            if (result == null) {
                response.abort();
            }
        }
    } catch (IOException e) {
        throw new QueryEvaluationException(e);
    }
}

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

/**
 * Writes out the transformed content from the downstream site.
 *//*from  w w  w  . j a v a2s.  co m*/
public void doView(final RenderRequest request, final RenderResponse response)
        throws PortletException, IOException {

    ResourceBundle resourceBundle = getPortletConfig().getResourceBundle(request.getLocale());

    // noop if window is minimised
    if (request.getWindowState().equals(WindowState.MINIMIZED)) {
        return;
    }

    response.setContentType("text/html");

    try {
        PortletSession session = request.getPortletSession();
        String portletId = response.getNamespace();
        PortletBridgeMemento tempMemento = (PortletBridgeMemento) session.getAttribute(mementoSessionKey,
                PortletSession.APPLICATION_SCOPE);
        if (tempMemento == null) {
            tempMemento = new DefaultPortletBridgeMemento(idParamKey, bridgeAuthenticator, initUrlFactory);
            session.setAttribute(mementoSessionKey, tempMemento, PortletSession.APPLICATION_SCOPE);
        }
        final PortletBridgeMemento memento = tempMemento;
        final PerPortletMemento perPortletMemento = memento.getPerPortletMemento(portletId);
        perPortletMemento.setPreferences(request);
        String urlId = request.getParameter(idParamKey);

        final BridgeRequest bridgeRequest;

        if (urlId != null) {
            bridgeRequest = memento.getBridgeRequest(urlId);
        } else {

            if (log.isDebugEnabled()) {
                log.debug("no bridge request found, using initUrl");
            }

            bridgeRequest = null;
        }

        if (urlId == null || bridgeRequest == null) {
            // this is the default start page for the portlet so go and
            // fetch it
            final URI initUrl = perPortletMemento.getInitUrl();
            httpClientTemplate.service(new GetMethod(initUrl.toString()), perPortletMemento,
                    new HttpClientCallback() {
                        public Object doInHttpClient(int statusCode, HttpMethodBase method) throws Throwable {
                            transformer.transform(memento, perPortletMemento, initUrl, request, response,
                                    new InputStreamReader(method.getResponseBodyAsStream(),
                                            method.getResponseCharSet()));
                            return null;
                        }
                    });
        } else {
            PortletBridgeContent content = perPortletMemento.dequeueContent(bridgeRequest.getId());
            if (content == null) {
                // we're rerendering
                httpClientTemplate.service(new GetMethod(bridgeRequest.getUrl().toString()), perPortletMemento,
                        new HttpClientCallback() {
                            public Object doInHttpClient(int statusCode, HttpMethodBase method)
                                    throws Throwable {
                                transformer.transform(memento, perPortletMemento, bridgeRequest.getUrl(),
                                        request, response, new InputStreamReader(
                                                method.getResponseBodyAsStream(), method.getResponseCharSet()));
                                return null;
                            }
                        });
            } else {
                // we have content, transform that
                transformer.transform(memento, perPortletMemento, bridgeRequest.getUrl(), request, response,
                        new StringReader(content.getContent()));
            }
        }

    } catch (ResourceException resourceException) {
        String format = MessageFormat.format(resourceBundle.getString(resourceException.getMessage()),
                resourceException.getArgs());
        throw new PortletException(format, resourceException.getCause());
    }
}