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

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

Introduction

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

Prototype

public abstract Header getResponseHeader(String paramString);

Source Link

Usage

From source file:org.eclipsetrader.yahoojapanfx.internal.core.connector.BackfillConnector.java

@Override
public IOHLC[] backfillHistory(IFeedIdentifier identifier, Date from, Date to, TimeSpan timeSpan) {
    List<OHLC> list = new ArrayList<OHLC>();

    String period = "";
    if (timeSpan.getUnits() == TimeSpan.Units.Days) {
        period = "1d";
    } else if (timeSpan.getUnits() == TimeSpan.Units.Minutes) {
        period = String.valueOf(timeSpan.getLength()) + "m";
    }//from ww w .  j a v  a  2  s.c  om

    HttpClient client = new HttpClient();
    try {
        HttpMethod method = Util.getPrepareHistoryFeedMethod(identifier);
        Util.setupProxy(client, method.getURI().getHost());

        client.executeMethod(method);

        BufferedReader in;
        if ((method.getResponseHeader("Content-Encoding") != null)
                && (method.getResponseHeader("Content-Encoding").getValue().equals("gzip"))) {
            in = new BufferedReader(
                    new InputStreamReader(new GZIPInputStream(method.getResponseBodyAsStream())));
        } else {
            in = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
        }
        String inputLine;
        String c = "";
        while ((inputLine = in.readLine()) != null) {
            if (inputLine.indexOf("YJFIN.c =") >= 0) {
                c = inputLine.substring(inputLine.indexOf("YJFIN.c =") + 11, inputLine.indexOf("\";"));
            }
        }
        in.close();

        method = Util.getHistoryFeedMethod(identifier, period, c);

        client.executeMethod(method);

        if ((method.getResponseHeader("Content-Encoding") != null)
                && (method.getResponseHeader("Content-Encoding").getValue().equals("gzip"))) {
            in = new BufferedReader(
                    new InputStreamReader(new GZIPInputStream(method.getResponseBodyAsStream())));
        } else {
            in = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
        }
        if (timeSpan.getUnits() == TimeSpan.Units.Days) {
            readHistoryStream(in, list);
        } else {
            readIntradayStream(in, list);
        }
        in.close();
    } catch (Exception e) {
        Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, "Error reading data", e); //$NON-NLS-1$
        Activator.log(status);
    }

    Collections.sort(list, new Comparator<OHLC>() {

        @Override
        public int compare(OHLC o1, OHLC o2) {
            return o1.getDate().compareTo(o2.getDate());
        }
    });

    for (Iterator<OHLC> iter = list.iterator(); iter.hasNext();) {
        OHLC ohlc = iter.next();
        if (ohlc.getDate().before(from) || ohlc.getDate().after(to)) {
            iter.remove();
        }
    }

    return list.toArray(new IOHLC[list.size()]);
}

From source file:org.eclipsetrader.yahoojapanfx.internal.core.connector.SnapshotConnector.java

protected void fetchLatestSnapshot(HttpClient client, String[] symbols) {
    try {//from www .j  a  v a  2 s .  co m
        HttpMethod method = Util.getSnapshotFeedMethod(streamingServer);

        BufferedReader in = null;
        try {
            client.executeMethod(method);

            if ((method.getResponseHeader("Content-Encoding") != null)
                    && (method.getResponseHeader("Content-Encoding").getValue().equals("gzip"))) {
                in = new BufferedReader(
                        new InputStreamReader(new GZIPInputStream(method.getResponseBodyAsStream())));
            } else {
                in = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
            }
            StringBuilder sb = new StringBuilder(1000);
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                sb.append(inputLine);
            }

            Calendar c = Calendar.getInstance();
            String year = String.valueOf(c.get(Calendar.YEAR));

            JSONObject obj = new JSONObject(sb.toString());
            JSONObject arate = obj.getJSONObject("rate");
            String date = obj.getString("date");
            //                String company = obj.getString("company");
            for (int i = 0; i < symbols.length; i++) {
                String symbol = (symbols[i].length() > 6 ? symbols[i].substring(0, 6) : symbols[i]);
                if (arate.has(symbol)) {
                    JSONObject o = arate.getJSONObject(symbol);
                    processSnapshotData(symbols[i], o, year + "/" + date);
                }
            }

        } catch (Exception e) {
            Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, "Error reading snapshot data", e); //$NON-NLS-1$
            Activator.log(status);
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (method != null) {
                    method.releaseConnection();
                }
            } catch (Exception e) {
                Status status = new Status(IStatus.WARNING, Activator.PLUGIN_ID, 0,
                        "Connection wasn't closed cleanly", e);
                Activator.log(status);
            }
        }

        wakeupNotifyThread();
    } catch (Exception e) {
        Activator.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, "Error reading snapshot data", e)); //$NON-NLS-1$
    }
}

From source file:org.executequery.http.spi.DefaultRemoteHttpClient.java

private RemoteHttpResponse handleRedirection(HttpMethod method) {

    Header locationHeader = method.getResponseHeader("location");
    if (locationHeader != null) {

        try {//from  w ww.  j a v  a 2 s  .  com

            URL url = new URL(locationHeader.getValue());
            return httpGetRequest(url.getHost(), url.getPath());

        } catch (MalformedURLException e) {

            throw new RemoteHttpClientException(e);
        }

    } else {

        throw new RemoteHttpClientException("Invalid redirection after method");
    }
}

From source file:org.exist.xquery.modules.httpclient.BaseHTTPClientFunction.java

/**
 * Takes the HTTP Response Body from the HTTP Method and attempts to insert it into the response tree we are building.
 *
 * <p>Conversion Preference - 1) Try and parse as XML, if successful returns a Node 2) Try and parse as HTML returning as XML compatible HTML, if
 * successful returns a Node 3) Return as base64Binary encoded data</p>
 *
 * @param   context  The context of the calling XQuery
 * @param   method   The HTTP Request Method
 * @param   builder  The MemTreeBuilder that is being used
 *
 * @throws  IOException     /* w ww .  j  a  v a2s  . c  om*/
 * @throws  XPathException  
 */
private void insertResponseBody(final XQueryContext context, final HttpMethod method,
        final MemTreeBuilder builder, final Map<String, Boolean> parserFeatures,
        final Map<String, String> parserProperties) throws IOException, XPathException {
    NodeImpl responseNode = null;

    final InputStream bodyAsStream = method.getResponseBodyAsStream();

    // check if there is a response body
    if (bodyAsStream != null) {

        CachingFilterInputStream cfis = null;
        FilterInputStreamCache cache = null;
        try {

            //we have to cache the input stream, so we can reread it, as we may use it twice (once for xml attempt and once for string attempt)
            cache = FilterInputStreamCacheFactory
                    .getCacheInstance(new FilterInputStreamCacheFactory.FilterInputStreamCacheConfiguration() {
                        @Override
                        public String getCacheClass() {
                            return (String) context.getBroker().getConfiguration()
                                    .getProperty(Configuration.BINARY_CACHE_CLASS_PROPERTY);
                        }
                    });

            cfis = new CachingFilterInputStream(cache, bodyAsStream);

            //mark the start of the stream
            cfis.mark(Integer.MAX_VALUE);

            // determine the type of the response document
            final Header responseContentType = method.getResponseHeader("Content-Type");

            final MimeType responseMimeType = getResponseMimeType(responseContentType);
            if (responseContentType != null) {
                builder.addAttribute(new QName("mimetype", null, null), responseContentType.getValue());
            }

            //try and parse the response as XML
            try {
                //we have to use CloseShieldInputStream otherwise the parser closes the stream and we cant later reread
                final InputStream shieldedInputStream = new CloseShieldInputStream(cfis);
                responseNode = (NodeImpl) ModuleUtils.streamToXML(context, shieldedInputStream);
                builder.addAttribute(new QName("type", null, null), "xml");
                responseNode.copyTo(null, new DocumentBuilderReceiver(builder));
            } catch (final SAXException se) {
                // could not parse to xml
                // not an error in itself, it will be treated either as HTML,
                // text or binary here below
                final String msg = "Request for URI '" + method.getURI().toString()
                        + "' Could not parse http response content as XML (will try html, text or fallback to binary): "
                        + se.getMessage();
                if (logger.isDebugEnabled()) {
                    logger.debug(msg, se);
                } else {
                    logger.info(msg);
                }
            } catch (final IOException ioe) {
                final String msg = "Request for URI '" + method.getURI().toString()
                        + "' Could not read http response content: " + ioe.getMessage();
                logger.error(msg, ioe);
                throw new XPathException(msg, ioe);
            }

            if (responseNode == null) {
                //response is NOT parseable as XML

                //is it a html document?
                if (responseMimeType.getName().equals(MimeType.HTML_TYPE.getName())) {

                    //html document
                    try {

                        //reset the stream to the start, as we need to reuse since attempting to parse to XML
                        cfis.reset();

                        //parse html to xml(html)

                        //we have to use CloseShieldInputStream otherwise the parser closes the stream and we cant later reread
                        final InputStream shieldedInputStream = new CloseShieldInputStream(cfis);

                        responseNode = (NodeImpl) ModuleUtils
                                .htmlToXHtml(context, method.getURI().toString(),
                                        new InputSource(shieldedInputStream), parserFeatures, parserProperties)
                                .getDocumentElement();
                        builder.addAttribute(new QName("type", null, null), "xhtml");
                        responseNode.copyTo(null, new DocumentBuilderReceiver(builder));
                    } catch (final URIException ue) {
                        throw new XPathException(this, ue.getMessage(), ue);
                    } catch (final SAXException se) {
                        //could not parse to xml(html)
                        logger.debug(
                                "Could not parse http response content from HTML to XML: " + se.getMessage(),
                                se);
                    }
                }
            }

            if (responseNode == null) {

                //reset the stream to the start, as we need to reuse since attempting to parse to HTML->XML
                cfis.reset();

                if (responseMimeType.getName().startsWith("text/")) {

                    // Assume it's a text body and URL encode it
                    builder.addAttribute(new QName("type", null, null), "text");
                    builder.addAttribute(new QName("encoding", null, null), "URLEncoded");

                    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    final byte buf[] = new byte[4096];
                    int read = -1;
                    while ((read = cfis.read(buf)) > -1) {
                        baos.write(buf);
                    }

                    builder.characters(URLEncoder.encode(EncodingUtil.getString(baos.toByteArray(),
                            ((HttpMethodBase) method).getResponseCharSet()), "UTF-8"));
                    baos.close();
                } else {

                    // Assume it's a binary body and Base64 encode it
                    builder.addAttribute(new QName("type", null, null), "binary");
                    builder.addAttribute(new QName("encoding", null, null), "Base64Encoded");

                    BinaryValue binary = null;
                    try {
                        binary = BinaryValueFromInputStream.getInstance(context, new Base64BinaryValueType(),
                                cfis);
                        builder.characters(binary.getStringValue());
                    } finally {
                        // free resources
                        if (binary != null) {
                            binary.destroy(context, null);
                        }
                    }
                }
            }
        } finally {
            if (cache != null) {
                try {
                    cache.invalidate();
                } catch (final IOException ioe) {
                    LOG.error(ioe.getMessage(), ioe);
                }
            }

            if (cfis != null) {
                try {
                    cfis.close();
                } catch (final IOException ioe) {
                    LOG.error(ioe.getMessage(), ioe);
                }
            }
        }
    }
}

From source file:org.geoserver.wps.executor.RemoteRequestInputProvider.java

@Override
protected Object getValueInternal(ProgressListener listener) throws Exception {
    InputReferenceType ref = input.getReference();
    URL destination = new URL(ref.getHref());

    HttpMethod method = null;
    GetMethod refMethod = null;//from  w  w  w  .java 2 s .com
    InputStream input = null;
    InputStream refInput = null;

    // execute the request
    listener.started();
    try {
        if ("file".equalsIgnoreCase(destination.getProtocol())) {
            File file = DataUtilities.urlToFile(destination);
            if (maxSize > 0 && maxSize < file.length()) {
                throw new WPSException("Input " + getInputId() + " size " + file.length()
                        + " exceeds maximum allowed size of " + maxSize, "NoApplicableCode", getInputId());
            }

            input = new FileInputStream(file);
        } else if ("http".equalsIgnoreCase(destination.getProtocol())) {
            // setup the client
            HttpClient client = new HttpClient();
            // setting timeouts (30 seconds, TODO: make this configurable)
            HttpConnectionManagerParams params = new HttpConnectionManagerParams();
            params.setSoTimeout(timeout);
            params.setConnectionTimeout(timeout);
            // TODO: make the http client a well behaved http client, no more than x connections
            // per server (x admin configurable maybe), persistent connections and so on
            HttpConnectionManager manager = new SimpleHttpConnectionManager();
            manager.setParams(params);
            client.setHttpConnectionManager(manager);

            // prepare either a GET or a POST request
            if (ref.getMethod() == null || ref.getMethod() == MethodType.GET_LITERAL) {
                GetMethod get = new GetMethod(ref.getHref());
                get.setFollowRedirects(true);
                method = get;
            } else {
                String encoding = ref.getEncoding();
                if (encoding == null) {
                    encoding = "UTF-8";
                }

                PostMethod post = new PostMethod(ref.getHref());
                Object body = ref.getBody();
                if (body == null) {
                    if (ref.getBodyReference() != null) {
                        URL refDestination = new URL(ref.getBodyReference().getHref());
                        if ("http".equalsIgnoreCase(refDestination.getProtocol())) {
                            // open with commons http client
                            refMethod = new GetMethod(ref.getBodyReference().getHref());
                            refMethod.setFollowRedirects(true);
                            client.executeMethod(refMethod);
                            refInput = refMethod.getResponseBodyAsStream();
                        } else {
                            // open with the built-in url management
                            URLConnection conn = refDestination.openConnection();
                            conn.setConnectTimeout(timeout);
                            conn.setReadTimeout(timeout);
                            refInput = conn.getInputStream();
                        }
                        post.setRequestEntity(
                                new InputStreamRequestEntity(refInput, complexPPIO.getMimeType()));
                    } else {
                        throw new WPSException("A POST request should contain a non empty body");
                    }
                } else if (body instanceof String) {
                    post.setRequestEntity(
                            new StringRequestEntity((String) body, complexPPIO.getMimeType(), encoding));
                } else {
                    throw new WPSException("The request body should be contained in a CDATA section, "
                            + "otherwise it will get parsed as XML instead of being preserved as is");

                }
                method = post;
            }
            // add eventual extra headers
            if (ref.getHeader() != null) {
                for (Iterator it = ref.getHeader().iterator(); it.hasNext();) {
                    HeaderType header = (HeaderType) it.next();
                    method.setRequestHeader(header.getKey(), header.getValue());
                }
            }
            int code = client.executeMethod(method);

            if (code == 200) {
                try {
                    Header length = method.getResponseHeader("Content-Lenght");
                    if (maxSize > 0 && length != null && Long.parseLong(length.getValue()) > maxSize) {
                        throw new WPSException(
                                "Input " + getInputId() + " size " + length.getValue()
                                        + " exceeds maximum allowed size of " + maxSize
                                        + " according to HTTP Content-Lenght response header",
                                "NoApplicableCode", getInputId());
                    }
                } catch (NumberFormatException e) {
                    LOGGER.log(Level.FINE, "Failed to parse content lenght to check input limits respect, "
                            + "moving on and checking data as it comes in", e);
                }
                input = method.getResponseBodyAsStream();
                if (maxSize > 0) {
                    input = new MaxSizeInputStream(input, getInputId(), maxSize);
                }
            } else {
                throw new WPSException("Error getting remote resources from " + ref.getHref() + ", http error "
                        + code + ": " + method.getStatusText());
            }
        } else {
            // use the normal url connection methods then...
            URLConnection conn = destination.openConnection();
            conn.setConnectTimeout(timeout);
            conn.setReadTimeout(timeout);
            input = conn.getInputStream();

            if (maxSize > 0) {
                input = new MaxSizeInputStream(input, getInputId(), maxSize);
            }
        }

        // actually parse the data
        if (input != null) {
            CancellingInputStream is = new CancellingInputStream(input, listener);
            return complexPPIO.decode(is);
        } else {
            throw new WPSException("Could not find a mean to read input " + inputId);
        }
    } finally {
        listener.progress(100);
        listener.complete();
        // make sure to close the connection and streams no matter what
        if (refInput != null) {
            refInput.close();
        }
        if (input != null) {
            input.close();
        }
        if (method != null) {
            method.releaseConnection();
        }
        if (refMethod != null) {
            refMethod.releaseConnection();
        }
    }
}

From source file:org.httpobjects.tck.IntegrationTest.java

private void assertResource(HttpMethod method, String expectedBody, int expectedResponseCode,
        HeaderSpec... header) {/*from   w  w w .  jav  a2s  .c  o m*/
    try {
        HttpClient client = new HttpClient();
        int response = client.executeMethod(method);

        Assert.assertEquals(expectedResponseCode, response);
        if (expectedBody != null)
            Assert.assertEquals(expectedBody, method.getResponseBodyAsString());

        if (header != null) {
            for (HeaderSpec next : header) {
                Header h = method.getResponseHeader(next.name);
                Assert.assertNotNull("Expected a \"" + next.name + "\" value of \"" + next.value + "\"", h);
                Assert.assertEquals(next.value, h.getValue());
            }
        }
    } catch (HttpException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.infoscoop.request.filter.ProxyFilterContainer.java

public final int invoke(HttpClient client, HttpMethod method, ProxyRequest request) throws Exception {
    int preStatus = prepareInvoke(client, method, request);
    switch (preStatus) {
    case 0://from w  ww .j  a v  a  2  s .  c  o m
        break;
    case EXECUTE_POST_STATUS:
        doFilterChain(request, request.getResponseBody());
    default:
        return preStatus;
    }
    // copy headers sent target server
    List ignoreHeaderNames = request.getIgnoreHeaders();
    List allowedHeaderNames = request.getAllowedHeaders();
    boolean allowAllHeader = false;

    Proxy proxy = request.getProxy();
    if (proxy != null) {
        allowAllHeader = proxy.isAllowAllHeader();
        if (!allowAllHeader)
            allowedHeaderNames.addAll(proxy.getAllowedHeaders());
    }

    AuthenticatorUtil.doAuthentication(client, method, request);

    StringBuffer headersSb = new StringBuffer();
    for (String name : request.getRequestHeaders().keySet()) {

        String value = request.getRequestHeader(name);
        String lowname = name.toLowerCase();

        if (!allowAllHeader && !allowedHeaderNames.contains(lowname))
            continue;

        if (ignoreHeaderNames.contains(lowname))
            continue;

        if ("cookie".equalsIgnoreCase(name)) {
            if (proxy.getSendingCookies() != null) {
                value = RequestUtil.removeCookieParam(value, proxy.getSendingCookies());
            }
        }

        if ("if-modified-since".equalsIgnoreCase(name) && "Thu, 01 Jun 1970 00:00:00 GMT".equals(value))
            continue;

        method.addRequestHeader(new Header(name, value));
        headersSb.append(name + "=" + value + ",  ");
    }

    int cacheStatus = getCache(client, method, request);
    if (cacheStatus != 0)
        return cacheStatus;

    if (log.isInfoEnabled())
        log.info("RequestHeader: " + headersSb);

    // execute http method and process redirect
    method.setFollowRedirects(false);

    client.executeMethod(method);

    int statusCode = method.getStatusCode();

    for (int i = 0; statusCode == HttpStatus.SC_MOVED_TEMPORARILY
            || statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_SEE_OTHER
            || statusCode == HttpStatus.SC_TEMPORARY_REDIRECT; i++) {

        // connection release
        method.releaseConnection();

        if (i == 5) {
            log.error("The circular redirect is limited by five times.");
            return 500;
        }

        Header location = method.getResponseHeader("Location");
        String redirectUrl = location.getValue();

        // According to 2,068 1.1 rfc http spec, we cannot appoint the relative URL,
        // but microsoft.com gives back the relative URL.
        if (redirectUrl.startsWith("/")) {
            URI baseURI = method.getURI();
            baseURI.setPath(redirectUrl);

            redirectUrl = baseURI.toString();
        }

        //method.setURI(new URI(redirectUrl, false));
        Header[] headers = method.getRequestHeaders();
        method = new GetMethod(redirectUrl);
        for (int j = 0; j < headers.length; j++) {
            String headerName = headers[j].getName();
            if (!headerName.equalsIgnoreCase("content-length") && !headerName.equalsIgnoreCase("authorization"))
                method.setRequestHeader(headers[j]);
        }
        AuthenticatorUtil.doAuthentication(client, method, request);
        method.setRequestHeader("authorization", request.getRequestHeader("Authorization"));
        method.setFollowRedirects(false);
        client.executeMethod(method);
        statusCode = method.getStatusCode();
        request.setRedirectURL(redirectUrl);

        if (log.isInfoEnabled())
            log.info("Redirect " + request.getTargetURL() + " to " + location + ".");
    }

    // copy response headers to proxyReqeust
    Header[] headers = method.getResponseHeaders();
    for (int i = 0; i < headers.length; i++) {
        request.putResponseHeader(headers[i].getName(), headers[i].getValue());
    }

    if (log.isInfoEnabled())
        log.info("Original Status:" + statusCode);

    // check response code
    if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
        log.error("Proxy Authentication Required. Confirm ajax proxy setting.");
        throw new Exception(
                "Http Status 407, Proxy Authentication Required. Please contuct System Administrator.");
    }
    if (statusCode == HttpStatus.SC_NOT_MODIFIED || statusCode == HttpStatus.SC_RESET_CONTENT) {
        return statusCode;
    } else if (statusCode < 200 || statusCode >= 300) {
        request.setResponseBody(method.getResponseBodyAsStream());
        return statusCode;
    }

    // process response body
    InputStream responseStream = null;
    if (statusCode != HttpStatus.SC_NO_CONTENT) {
        if (request.allowUserPublicCache()) {
            byte[] responseBody = method.getResponseBody();

            Map<String, List<String>> responseHeaders = request.getResponseHeaders();
            if (request.getRedirectURL() != null)
                responseHeaders.put("X-IS-REDIRECTED-FROM",
                        Arrays.asList(new String[] { request.getRedirectURL() }));
            if (method instanceof GetMethod) {
                putCache(request.getOriginalURL(), new ByteArrayInputStream(responseBody), responseHeaders);
            }

            responseStream = new ByteArrayInputStream(responseBody);
        } else {
            responseStream = method.getResponseBodyAsStream();
        }
    }
    doFilterChain(request, responseStream);

    return statusCode != HttpStatus.SC_NO_CONTENT ? method.getStatusCode() : 200;
}

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/*from w  ww .  j a va2 s  . co  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.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 {/*www. j  a v  a2s .c  om*/
        return method.getResponseBodyAsStream();
    }
}

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

/**
* @param urlStr//from   w  ww  .jav  a 2  s .c  om
* @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();
        }
    }
}