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

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

Introduction

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

Prototype

public abstract InputStream getResponseBodyAsStream() throws IOException;

Source Link

Usage

From source file:org.jasig.portlet.weather.dao.worldwide.WorldWeatherOnlineDaoImpl.java

public Collection<Location> find(String location) {
    final String url = FIND_URL.replace("@KEY@", key).replace("@QUERY@",
            QuietUrlCodec.encode(location, Constants.URL_ENCODING));

    HttpMethod getMethod = new GetMethod(url);
    InputStream inputStream = null;
    try {/*from  w  ww .j a  v a2  s .  c o m*/
        // Execute the method.
        int statusCode = httpClient.executeMethod(getMethod);
        if (statusCode != HttpStatus.SC_OK) {
            final String statusText = getMethod.getStatusText();
            throw new DataRetrievalFailureException(
                    "get of '" + url + "' failed with status '" + statusCode + "' due to '" + statusText + "'");
        }

        // Read the response body
        inputStream = getMethod.getResponseBodyAsStream();

        List<Location> locations = deserializeSearchResults(inputStream);

        return locations;

    } catch (HttpException e) {
        throw new RuntimeException(
                "http protocol exception while getting data from weather service from: " + url, e);
    } catch (IOException e) {
        throw new RuntimeException("IO exception while getting data from weather service from: " + url, e);
    } catch (JAXBException e) {
        throw new RuntimeException("Parsing exception while getting data from weather service from: " + url, e);
    } finally {
        //try to close the inputstream
        IOUtils.closeQuietly(inputStream);
        //release the connection
        getMethod.releaseConnection();
    }
}

From source file:org.jasig.portlet.weather.dao.worldwide.WorldWeatherOnlineDaoImpl.java

protected Object getAndDeserialize(String url, TemperatureUnit unit) {
    HttpMethod getMethod = new GetMethod(url);
    InputStream inputStream = null;
    try {//from w ww  .  j  a v  a  2  s.  com
        // Execute the method.
        int statusCode = httpClient.executeMethod(getMethod);
        if (statusCode != HttpStatus.SC_OK) {
            final String statusText = getMethod.getStatusText();
            throw new DataRetrievalFailureException(
                    "get of '" + url + "' failed with status '" + statusCode + "' due to '" + statusText + "'");
        }

        // Read the response body
        inputStream = getMethod.getResponseBodyAsStream();

        Weather weather = deserializeWeatherResult(inputStream, unit);

        return weather;

    } catch (HttpException e) {
        throw new RuntimeException(
                "http protocol exception while getting data from weather service from: " + url, e);
    } catch (IOException e) {
        throw new RuntimeException("IO exception while getting data from weather service from: " + url, e);
    } catch (JAXBException e) {
        throw new RuntimeException("Parsing exception while getting data from weather service from: " + url, e);
    } catch (ParseException e) {
        throw new RuntimeException("Parsing exception while getting data from weather service from: " + url, e);
    } finally {
        //try to close the inputstream
        IOUtils.closeQuietly(inputStream);
        //release the connection
        getMethod.releaseConnection();
    }
}

From source file:org.jasig.portlet.weather.dao.yahoo.YahooWeatherDaoImpl.java

public Collection<Location> find(String location) {
    if ((key == null) || (key.length() == 0)) {
        MessageSourceResolvable resolvable = new DefaultMessageSourceResolvable(
                new String[] { ERR_API_MISSING_KEY, ERR_GENERAL_KEY });
        throw new InvalidConfigurationException(messageSource.getMessage(resolvable, Locale.getDefault()));
    }/* w  w w  .  j  a  va  2s.co m*/

    final String url = FIND_URL.replace("@KEY@", key).replace("@QUERY@",
            QuietUrlCodec.encode(location, Constants.URL_ENCODING));

    HttpMethod getMethod = new GetMethod(url);
    InputStream inputStream = null;
    try {
        // Execute the method.
        int statusCode = httpClient.executeMethod(getMethod);
        if (statusCode != HttpStatus.SC_OK) {
            final String statusText = getMethod.getStatusText();
            throw new DataRetrievalFailureException(
                    "get of '" + url + "' failed with status '" + statusCode + "' due to '" + statusText + "'");
        }

        // Read the response body
        inputStream = getMethod.getResponseBodyAsStream();

        List<Location> locations = locationParsingService.parseLocations(inputStream);

        return locations;

    } catch (HttpException e) {
        throw new RuntimeException(
                "http protocol exception while getting data from weather service from: " + url, e);
    } catch (IOException e) {
        throw new RuntimeException("IO exception while getting data from weather service from: " + url, e);
    } finally {
        //try to close the inputstream
        IOUtils.closeQuietly(inputStream);
        //release the connection
        getMethod.releaseConnection();
    }
}

From source file:org.jasig.portlet.weather.dao.yahoo.YahooWeatherDaoImpl.java

protected Object getAndDeserialize(String url) {
    HttpMethod getMethod = new GetMethod(url);
    InputStream inputStream = null;
    try {//from   ww  w.  ja v  a2s .co  m
        // Execute the method.
        int statusCode = httpClient.executeMethod(getMethod);
        if (statusCode != HttpStatus.SC_OK) {
            final String statusText = getMethod.getStatusText();
            throw new DataRetrievalFailureException(
                    "get of '" + url + "' failed with status '" + statusCode + "' due to '" + statusText + "'");
        }

        // Read the response body
        inputStream = getMethod.getResponseBodyAsStream();
        return weatherParsingService.parseWeather(inputStream);
    } catch (HttpException e) {
        throw new RuntimeException(
                "http protocol exception while getting data from weather service from: " + url, e);
    } catch (IOException e) {
        throw new RuntimeException("IO exception while getting data from weather service from: " + url, e);
    } finally {
        //try to close the inputstream
        IOUtils.closeQuietly(inputStream);
        //release the connection
        getMethod.releaseConnection();
    }
}

From source file:org.jboss.orion.openshift.server.proxy.JsonProxyServlet.java

/**
 * Executes the {@link HttpMethod} passed in and sends the proxy response
 * back to the client via the given {@link javax.servlet.http.HttpServletResponse}
 *
 * @param proxyDetails/*  w  w  w  . ja v a  2  s .c o  m*/
 * @param httpMethodProxyRequest An object representing the proxy request to be made
 * @param httpServletResponse    An object by which we can send the proxied
 *                               response back to the client
 * @throws java.io.IOException            Can be thrown by the {@link HttpClient}.executeMethod
 * @throws javax.servlet.ServletException Can be thrown to indicate that another error has occurred
 */
private void executeProxyRequest(ProxyDetails proxyDetails, HttpMethod httpMethodProxyRequest,
        HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws IOException, ServletException {
    httpMethodProxyRequest.setDoAuthentication(false);
    httpMethodProxyRequest.setFollowRedirects(false);

    // Create a default HttpClient
    HttpClient httpClient = proxyDetails.createHttpClient(httpMethodProxyRequest);

    // Execute the request
    int intProxyResponseCode = 500;
    try {
        intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest);
    } catch (Exception e) {
        e.printStackTrace();
    }

    // Check if the proxy response is a redirect
    // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect
    // Hooray for open source software
    if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */
            && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) {
        String stringStatusCode = Integer.toString(intProxyResponseCode);
        String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
        if (stringLocation == null) {
            throw new ServletException("Received status code: " + stringStatusCode + " but no "
                    + STRING_LOCATION_HEADER + " header was found in the response");
        }
        // Modify the redirect to go to this proxy servlet rather that the proxied host
        String stringMyHostName = httpServletRequest.getServerName();
        if (httpServletRequest.getServerPort() != 80) {
            stringMyHostName += ":" + httpServletRequest.getServerPort();
        }
        stringMyHostName += httpServletRequest.getContextPath();
        httpServletResponse.sendRedirect(stringLocation
                .replace(proxyDetails.getProxyHostAndPort() + proxyDetails.getProxyPath(), stringMyHostName));
        return;
    } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) {
        // 304 needs special handling.  See:
        // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
        // We get a 304 whenever passed an 'If-Modified-Since'
        // header and the data on disk has not changed; server
        // responds w/ a 304 saying I'm not going to send the
        // body because the file has not changed.
        httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0);
        httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // Pass the response code back to the client
    httpServletResponse.setStatus(intProxyResponseCode);

    // Pass response headers back to the client
    Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();
    for (Header header : headerArrayResponse) {
        if (!ProxySupport.isHopByHopHeader(header.getName())) {
            if (ProxySupport.isSetCookieHeader(header)) {
                HttpProxyRule proxyRule = proxyDetails.getProxyRule();
                String setCookie = ProxySupport.replaceCookieAttributes(header.getValue(),
                        proxyRule.getCookiePath(), proxyRule.getCookieDomain());
                httpServletResponse.setHeader(header.getName(), setCookie);
            } else {
                httpServletResponse.setHeader(header.getName(), header.getValue());
            }
        }
    }

    // check if we got data, that is either the Content-Length > 0
    // or the response code != 204
    int code = httpMethodProxyRequest.getStatusCode();
    boolean noData = code == HttpStatus.SC_NO_CONTENT;
    if (!noData) {
        String length = httpServletRequest.getHeader(STRING_CONTENT_LENGTH_HEADER_NAME);
        if (length != null && "0".equals(length.trim())) {
            noData = true;
        }
    }

    if (!noData) {
        // Send the content to the client
        InputStream inputStreamProxyResponse = httpMethodProxyRequest.getResponseBodyAsStream();
        BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStreamProxyResponse);
        OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream();
        int intNextByte;
        while ((intNextByte = bufferedInputStream.read()) != -1) {
            outputStreamClientResponse.write(intNextByte);
        }
    }
}

From source file:org.jboss.web.loadbalancer.Loadbalancer.java

protected void copyServerResponse(HttpServletResponse response, HttpMethod method) throws IOException {

    InputStream bodyStream = method.getResponseBodyAsStream();

    // any response?
    if (bodyStream == null) {
        log.debug("No request body");
        return;/*from  www .j  a  v  a 2  s  . co  m*/
    }

    byte[] buffer = new byte[2048];
    int numBytes;
    OutputStream out = response.getOutputStream();

    // copy the response
    while ((numBytes = bodyStream.read(buffer)) != -1) {
        out.write(buffer, 0, numBytes);
        if (log.isDebugEnabled()) {
            log.debug("Copied " + numBytes + " bytes");
        }
    }
}

From source file:org.jetbrains.tfsIntegration.webservice.WebServiceHelper.java

private static InputStream getInputStream(HttpMethod method) throws IOException {
    Header contentType = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_TYPE);
    if (contentType != null && CONTENT_TYPE_GZIP.equalsIgnoreCase(contentType.getValue())) {
        return new GZIPInputStream(method.getResponseBodyAsStream());
    } else {//from w w w  . j  a  v  a 2s  .com
        return method.getResponseBodyAsStream();
    }
}

From source file:org.jivesoftware.util.HttpClientWithTimeoutFeedFetcher.java

/**
* @param urlStr/*from w  ww  . ja  v  a  2 s  .c o  m*/
* @param method
* @return SyndFeed or None
* @throws IOException
* @throws HttpException
* @throws FetcherException
* @throws FeedException
*/
private static SyndFeed retrieveFeed(String urlStr, HttpMethod method)
        throws IOException, HttpException, FetcherException, FeedException {

    InputStream stream = null;
    if ((method.getResponseHeader("Content-Encoding") != null)
            && ("gzip".equalsIgnoreCase(method.getResponseHeader("Content-Encoding").getValue()))) {
        stream = new GZIPInputStream(method.getResponseBodyAsStream());
    } else {
        stream = method.getResponseBodyAsStream();
    }
    try {
        XmlReader reader = null;
        if (method.getResponseHeader("Content-Type") != null) {
            reader = new XmlReader(stream, method.getResponseHeader("Content-Type").getValue(), true);
        } else {
            reader = new XmlReader(stream, true);
        }
        return new SyndFeedInput().build(reader);
    } finally {
        if (stream != null) {
            stream.close();
        }
    }
}

From source file:org.kalypso.util.net.URLGetter.java

/**
 * @see org.kalypso.contribs.eclipse.jface.operation.ICoreRunnableWithProgress#execute(org.eclipse.core.runtime.IProgressMonitor)
 *///from w  ww  .  j  av a2s.c om
@Override
public IStatus execute(final IProgressMonitor monitor) {
    final String urlAsString = m_url.toString();
    final HttpMethod method = new GetMethod(urlAsString);
    // do not forget the next line!
    method.setDoAuthentication(true);

    final Thread thread = new Thread() {
        @Override
        public void run() {
            try {
                final HttpClient httpClient = getHttpClient();
                httpClient.executeMethod(method);
                setResult(method.getResponseBodyAsStream());
            } catch (final IOException e) {
                final IStatus status;

                String responseBodyAsString = Messages.getString("org.kalypso.util.net.URLGetter.1"); //$NON-NLS-1$
                try {
                    responseBodyAsString = method.getResponseBodyAsString();
                } catch (final IOException e1) {
                    final IStatus status2 = StatusUtilities.statusFromThrowable(e1);
                    KalypsoGisPlugin.getDefault().getLog().log(status2);
                }

                String message = Messages.getString("org.kalypso.util.net.URLGetter.2") + urlAsString; //$NON-NLS-1$
                if (responseBodyAsString != null && !responseBodyAsString.isEmpty())
                    message += "\n" + responseBodyAsString; //$NON-NLS-1$

                status = new Status(IStatus.ERROR, KalypsoGisPlugin.getId(), 0, message, e);
                setStatus(status);
            }
        }
    };

    monitor.beginTask(urlAsString, IProgressMonitor.UNKNOWN);
    monitor.subTask(Messages.getString("org.kalypso.util.net.URLGetter.4")); //$NON-NLS-1$
    thread.start();
    while (thread.isAlive()) {
        try {
            Thread.sleep(100);
        } catch (final InterruptedException e1) {
            // should never happen, ignore
            e1.printStackTrace();
        }

        final String statusText;
        final StatusLine statusLine = method.getStatusLine();
        if (statusLine == null)
            statusText = Messages.getString("org.kalypso.util.net.URLGetter.5"); //$NON-NLS-1$
        else
            statusText = method.getStatusText();

        monitor.subTask(statusText);
        monitor.worked(1);
        if (monitor.isCanceled()) {
            // TODO: this does not stop the thread!
            thread.interrupt();

            monitor.done();
            return Status.CANCEL_STATUS;
        }
    }

    monitor.done();
    return m_status;
}

From source file:org.krakenapps.pkg.HttpWagon.java

public static InputStream openDownloadStream(URL url, boolean useAuth, String username, String password)
        throws IOException {
    Logger logger = LoggerFactory.getLogger(HttpWagon.class.getName());
    logger.trace("http wagon: downloading {}", url);

    HttpClient client = new HttpClient();
    if (useAuth) {
        client.getParams().setAuthenticationPreemptive(true);
        Credentials defaultcreds = new UsernamePasswordCredentials(username, password);
        client.getState().setCredentials(new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM),
                defaultcreds);//w w w . j av a  2  s . c  om
    }

    HttpMethod method = new GetMethod(url.toString());

    int socketTimeout = getSocketTimeout();
    int connectionTimeout = getConnectTimeout();

    client.getParams().setParameter("http.socket.timeout", socketTimeout);
    client.getParams().setParameter("http.connection.timeout", connectionTimeout);
    client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, null);

    int statusCode = client.executeMethod(method);

    if (statusCode != HttpStatus.SC_OK) {
        throw new IOException("method failed: " + method.getStatusLine());
    }

    return method.getResponseBodyAsStream();
}