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.methodize.nntprss.feed.Channel.java

/**
 * Retrieves the latest RSS doc from the remote site
 *///from   w  w  w.jav a2s .co  m
public synchronized void poll() {
    // Use method-level variable
    // Guard against change in history mid-poll
    polling = true;

    //      boolean keepHistory = historical;
    long keepExpiration = expiration;

    lastPolled = new Date();

    int statusCode = -1;
    HttpMethod method = null;
    String urlString = url.toString();
    try {
        HttpClient httpClient = getHttpClient();
        channelManager.configureHttpClient(httpClient);
        HttpResult result = null;

        try {

            connected = true;
            boolean redirected = false;
            int count = 0;
            do {
                URL currentUrl = new URL(urlString);
                method = new GetMethod(urlString);
                method.setRequestHeader("User-agent", AppConstants.getUserAgent());
                method.setRequestHeader("Accept-Encoding", "gzip");
                method.setFollowRedirects(false);
                method.setDoAuthentication(true);

                // ETag
                if (lastETag != null) {
                    method.setRequestHeader("If-None-Match", lastETag);
                }

                // Last Modified
                if (lastModified != 0) {
                    final String NAME = "If-Modified-Since";
                    //defend against such fun like net.freeroller.rickard got If-Modified-Since "Thu, 24 Aug 2028 12:29:54 GMT"
                    if (lastModified < System.currentTimeMillis()) {
                        final String DATE = httpDate.format(new Date(lastModified));
                        method.setRequestHeader(NAME, DATE);
                        log.debug("channel " + this.name + " using " + NAME + " " + DATE); //ALEK
                    }
                }

                method.setFollowRedirects(false);
                method.setDoAuthentication(true);

                HostConfiguration hostConfig = new HostConfiguration();
                hostConfig.setHost(currentUrl.getHost(), currentUrl.getPort(), currentUrl.getProtocol());

                result = executeHttpRequest(httpClient, hostConfig, method);
                statusCode = result.getStatusCode();
                if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
                        || statusCode == HttpStatus.SC_MOVED_TEMPORARILY
                        || statusCode == HttpStatus.SC_SEE_OTHER
                        || statusCode == HttpStatus.SC_TEMPORARY_REDIRECT) {

                    redirected = true;
                    // Resolve against current URI - may be a relative URI
                    try {
                        urlString = new java.net.URI(urlString).resolve(result.getLocation()).toString();
                    } catch (URISyntaxException use) {
                        // Fall back to just using location from result
                        urlString = result.getLocation();
                    }
                    if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY && channelManager.isObserveHttp301()) {
                        try {
                            url = new URL(urlString);
                            if (log.isInfoEnabled()) {
                                log.info("Channel = " + this.name
                                        + ", updated URL from HTTP Permanent Redirect");
                            }
                        } catch (MalformedURLException mue) {
                            // Ignore URL permanent redirect for now...                        
                        }
                    }
                } else {
                    redirected = false;
                }

                //               method.getResponseBody();
                //               method.releaseConnection();
                count++;
            } while (count < 5 && redirected);

        } catch (HttpRecoverableException hre) {
            if (log.isDebugEnabled()) {
                log.debug("Channel=" + name + " - Temporary Http Problem - " + hre.getMessage());
            }
            status = STATUS_CONNECTION_TIMEOUT;
            statusCode = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        } catch (ConnectException ce) {
            // @TODO Might also be a connection refused - not only a timeout...
            if (log.isDebugEnabled()) {
                log.debug("Channel=" + name + " - Connection Timeout, skipping - " + ce.getMessage());
            }
            status = STATUS_CONNECTION_TIMEOUT;
            statusCode = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        } catch (UnknownHostException ue) {
            if (log.isDebugEnabled()) {
                log.debug("Channel=" + name + " - Unknown Host Exception, skipping");
            }
            status = STATUS_UNKNOWN_HOST;
            statusCode = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        } catch (NoRouteToHostException re) {
            if (log.isDebugEnabled()) {
                log.debug("Channel=" + name + " - No Route To Host Exception, skipping");
            }
            status = STATUS_NO_ROUTE_TO_HOST;
            statusCode = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        } catch (SocketException se) {
            // e.g. Network is unreachable            
            if (log.isDebugEnabled()) {
                log.debug("Channel=" + name + " - Socket Exception, skipping");
            }
            status = STATUS_SOCKET_EXCEPTION;
            statusCode = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        }

        // Only process if ok - if not ok (e.g. not modified), don't do anything
        if (connected && statusCode == HttpStatus.SC_OK) {

            PushbackInputStream pbis = new PushbackInputStream(new ByteArrayInputStream(result.getResponse()),
                    PUSHBACK_BUFFER_SIZE);
            skipBOM(pbis);
            BufferedInputStream bis = new BufferedInputStream(pbis);
            DocumentBuilder db = AppConstants.newDocumentBuilder();

            try {
                Document rssDoc = null;
                if (!parseAtAllCost) {
                    try {
                        rssDoc = db.parse(bis);
                    } catch (InternalError ie) {
                        // Crimson library throws InternalErrors
                        if (log.isDebugEnabled()) {
                            log.debug("InternalError thrown by Crimson", ie);
                        }
                        throw new SAXException("InternalError thrown by Crimson: " + ie.getMessage());
                    }
                } else {
                    // Parse-at-all-costs selected
                    // Read in document to local array - may need to parse twice
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    byte[] buf = new byte[1024];
                    int bytesRead = bis.read(buf);
                    while (bytesRead > -1) {
                        if (bytesRead > 0) {
                            bos.write(buf, 0, bytesRead);
                        }
                        bytesRead = bis.read(buf);
                    }
                    bos.flush();
                    bos.close();

                    byte[] rssDocBytes = bos.toByteArray();

                    try {
                        // Try the XML document parser first - just in case
                        // the doc is well-formed
                        rssDoc = db.parse(new ByteArrayInputStream(rssDocBytes));
                    } catch (SAXParseException spe) {
                        if (log.isDebugEnabled()) {
                            log.debug("XML parse failed, trying tidy");
                        }
                        // Fallback to parse-at-all-costs parser
                        rssDoc = LooseParser.parse(new ByteArrayInputStream(rssDocBytes));
                    }
                }

                processChannelDocument(expiration, rssDoc);

                // Update last modified / etag from headers
                //               lastETag = httpCon.getHeaderField("ETag");
                //               lastModified = httpCon.getHeaderFieldDate("Last-Modified", 0);

                Header hdrETag = method.getResponseHeader("ETag");
                lastETag = hdrETag != null ? hdrETag.getValue() : null;

                Header hdrLastModified = method.getResponseHeader("Last-Modified");
                lastModified = hdrLastModified != null ? parseHttpDate(hdrLastModified.getValue()) : 0;
                log.debug("channel " + this.name + " parsed Last-Modifed " + hdrLastModified + " to "
                        + (lastModified != 0 ? "" + (new Date(lastModified)) : "" + lastModified)); //ALEK

                status = STATUS_OK;
            } catch (SAXParseException spe) {
                if (log.isEnabledFor(Priority.WARN)) {
                    log.warn("Channel=" + name + " - Error parsing RSS document - check feed");
                }
                status = STATUS_INVALID_CONTENT;
            }

            bis.close();

            // end if response code == HTTP_OK
        } else if (connected && statusCode == HttpStatus.SC_NOT_MODIFIED) {
            if (log.isDebugEnabled()) {
                log.debug("Channel=" + name + " - HTTP_NOT_MODIFIED, skipping");
            }
            status = STATUS_OK;
        } else if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
            if (log.isEnabledFor(Priority.WARN)) {
                log.warn("Channel=" + name + " - Proxy authentication required");
            }
            status = STATUS_PROXY_AUTHENTICATION_REQUIRED;
        } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
            if (log.isEnabledFor(Priority.WARN)) {
                log.warn("Channel=" + name + " - Authentication required");
            }
            status = STATUS_USER_AUTHENTICATION_REQUIRED;
        }

        // Update channel in database...
        channelDAO.updateChannel(this);

    } catch (FileNotFoundException fnfe) {
        if (log.isEnabledFor(Priority.WARN)) {
            log.warn("Channel=" + name + " - File not found returned by web server - check feed");
        }
        status = STATUS_NOT_FOUND;
    } catch (Exception e) {
        if (log.isEnabledFor(Priority.WARN)) {
            log.warn("Channel=" + name + " - Exception while polling channel", e);
        }
    } catch (NoClassDefFoundError ncdf) {
        // Throw if SSL / redirection to HTTPS
        if (log.isEnabledFor(Priority.WARN)) {
            log.warn("Channel=" + name + " - NoClassDefFound", ncdf);
        }
    } finally {
        connected = false;
        polling = false;
    }

}

From source file:org.methodize.nntprss.feed.Channel.java

/**
 * Executes HTTP request//from  w  w  w. ja v a2s  .c o  m
 * @param client
 * @param config
 * @param method
 */

private static HttpResult executeHttpRequest(HttpClient client, HostConfiguration config, HttpMethod method)
        throws HttpException, IOException {

    HttpResult result;
    int statusCode = -1;

    try {
        statusCode = client.executeMethod(config, method);

        //      while (statusCode == -1 && attempt < 3) {
        //         try {
        //            // execute the method.
        //            statusCode = client.executeMethod(config, method);
        //         } catch (HttpRecoverableException e) {
        //            log.(
        //               "A recoverable exception occurred, retrying."
        //                  + e.getMessage());
        //            method.releaseConnection();
        //            method.recycle();
        //            try {
        //               Thread.sleep(250);
        //            } catch(InterruptedException ie) {
        //            }
        //         } 
        //      }

        result = new HttpResult(statusCode);
        Header locationHeader = method.getResponseHeader("location");
        if (locationHeader != null) {
            result.setLocation(locationHeader.getValue());
        }

        if (statusCode == HttpStatus.SC_OK) {
            Header contentEncoding = method.getResponseHeader("Content-Encoding");
            if (contentEncoding != null && contentEncoding.getValue().equals("gzip")) {
                InputStream is = method.getResponseBodyAsStream();
                is = new GZIPInputStream(is);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buf = new byte[1024];
                int bytesRead;
                while ((bytesRead = is.read(buf)) > -1) {
                    if (bytesRead > 0) {
                        baos.write(buf, 0, bytesRead);
                    }
                }
                baos.flush();
                baos.close();
                is.close();
                result.setResponse(baos.toByteArray());
            } else {
                result.setResponse(method.getResponseBody());
            }
        } else {
            // Process response
            InputStream is = method.getResponseBodyAsStream();
            if (is != null) {
                byte[] buf = new byte[1024];
                while (is.read(buf) != -1)
                    ;
                is.close();
            }
            //   result.setResponse(method.getResponseBody());      
        }

        return result;
    } finally {
        method.releaseConnection();
    }
}

From source file:org.mozilla.zest.impl.ZestBasicRunner.java

private ZestResponse send(HttpClient httpclient, ZestRequest req) throws IOException {
    HttpMethod method;
    URI uri = new URI(req.getUrl().toString(), false);

    switch (req.getMethod()) {
    case "GET":
        method = new GetMethod(uri.toString());
        // Can only redirect on GETs
        method.setFollowRedirects(req.isFollowRedirects());
        break;/*from www. j  a  va2  s . c  om*/
    case "POST":
        method = new PostMethod(uri.toString());
        break;
    case "OPTIONS":
        method = new OptionsMethod(uri.toString());
        break;
    case "HEAD":
        method = new HeadMethod(uri.toString());
        break;
    case "PUT":
        method = new PutMethod(uri.toString());
        break;
    case "DELETE":
        method = new DeleteMethod(uri.toString());
        break;
    case "TRACE":
        method = new TraceMethod(uri.toString());
        break;
    default:
        throw new IllegalArgumentException("Method not supported: " + req.getMethod());
    }

    setHeaders(method, req.getHeaders());

    for (Cookie cookie : req.getCookies()) {
        // Replace any Zest variables in the value
        cookie.setValue(this.replaceVariablesInString(cookie.getValue(), false));
        httpclient.getState().addCookie(cookie);
    }

    if (req.getMethod().equals("POST")) {
        // The setRequestEntity call trashes any Content-Type specified, so record it and reapply it after
        Header contentType = method.getRequestHeader("Content-Type");
        RequestEntity requestEntity = new StringRequestEntity(req.getData(), null, null);

        ((PostMethod) method).setRequestEntity(requestEntity);

        if (contentType != null) {
            method.setRequestHeader(contentType);
        }
    }

    int code = 0;
    String responseHeader = null;
    String responseBody = null;
    Date start = new Date();
    try {
        this.debug(req.getMethod() + " : " + req.getUrl());
        code = httpclient.executeMethod(method);

        responseHeader = method.getStatusLine().toString() + "\r\n" + arrayToStr(method.getResponseHeaders());
        responseBody = method.getResponseBodyAsString();

    } finally {
        method.releaseConnection();
    }
    // Update the headers with the ones actually sent
    req.setHeaders(arrayToStr(method.getRequestHeaders()));

    if (method.getStatusCode() == 302 && req.isFollowRedirects() && !req.getMethod().equals("GET")) {
        // Follow the redirect 'manually' as the httpclient lib only supports them for GET requests
        method = new GetMethod(method.getResponseHeader("Location").getValue());
        // Just in case there are multiple redirects
        method.setFollowRedirects(req.isFollowRedirects());

        try {
            this.debug(req.getMethod() + " : " + req.getUrl());
            code = httpclient.executeMethod(method);

            responseHeader = method.getStatusLine().toString() + "\r\n"
                    + arrayToStr(method.getResponseHeaders());
            responseBody = method.getResponseBodyAsString();

        } finally {
            method.releaseConnection();
        }
    }

    return new ZestResponse(req.getUrl(), responseHeader, responseBody, code,
            new Date().getTime() - start.getTime());
}

From source file:org.mule.transport.http.functional.HttpKeepAliveFunctionalTestCase.java

private void runHttp10MethodAndAssertConnectionHeader(HttpMethod request, String expectedConnectionHeaderValue)
        throws Exception {
    int status = http10Client.executeMethod(request);
    assertEquals(HttpStatus.SC_OK, status);
    String connectionHeader = request.getResponseHeader(HttpConstants.HEADER_CONNECTION).getValue();
    assertNotNull(connectionHeader);/*from w  ww  . j  ava 2 s  .  c o m*/
    assertEquals(expectedConnectionHeaderValue, connectionHeader);
}

From source file:org.mule.transport.http.HttpClientMessageDispatcher.java

protected MuleMessage handleRedirect(HttpMethod method, MuleEvent event)
        throws HttpResponseException, MuleException, IOException {
    String followRedirects = (String) endpoint.getProperty("followRedirects");
    if (followRedirects == null || "false".equalsIgnoreCase(followRedirects)) {
        if (logger.isInfoEnabled()) {
            logger.info("Received a redirect, but followRedirects=false. Response code: "
                    + method.getStatusCode() + " " + method.getStatusText());
        }// w  w w.  j  a va 2 s. c o m
        return getResponseFromMethod(method, null);
    }
    Header locationHeader = method.getResponseHeader(HttpConstants.HEADER_LOCATION);
    if (locationHeader == null) {
        throw new HttpResponseException(method.getStatusText(), method.getStatusCode());
    }
    OutboundEndpoint out = new EndpointURIEndpointBuilder(locationHeader.getValue(),
            httpConnector.getMuleContext()).buildOutboundEndpoint();
    MuleEvent result = out.process(event);
    if (result != null && !VoidMuleEvent.getInstance().equals(result)) {
        return result.getMessage();
    } else {
        return null;
    }
}

From source file:org.mulgara.resolver.http.HttpContent.java

/**
 * Obtain a valid connection and follow redirects if necessary.
 * //from  w ww.j  a  v  a 2 s  .c  o  m
 * @param methodType request the headders (HEAD) or body (GET)
 * @return valid connection method. Can be null.
 * @throws NotModifiedException  if the content validates against the cache
 * @throws IOException  if there's difficulty communicating with the web site
 */
private HttpMethod establishConnection(int methodType) throws IOException, NotModifiedException {
    if (logger.isDebugEnabled())
        logger.debug("Establishing connection");

    HttpMethod method = getConnectionMethod(methodType);
    assert method != null;
    Header header = null;

    /*
      // Add cache validation headers to the request
      if (lastModifiedMap.containsKey(httpUri)) {
        String lastModified = (String) lastModifiedMap.get(httpUri);
        assert lastModified != null;
        method.addRequestHeader("If-Modified-Since", lastModified);
      }
            
      if (eTagMap.containsKey(httpUri)) {
        String eTag = (String) eTagMap.get(httpUri);
        assert eTag != null;
        method.addRequestHeader("If-None-Match", eTag);
      }
     */

    // Make the request
    if (logger.isDebugEnabled())
        logger.debug("Executing HTTP request");
    connection.open();
    method.execute(state, connection);
    if (logger.isDebugEnabled()) {
        logger.debug("Executed HTTP request, response code " + method.getStatusCode());
    }

    // Interpret the response header
    if (method.getStatusCode() == HttpStatus.SC_NOT_MODIFIED) {
        // cache has been validated
        throw new NotModifiedException(httpUri);
    } else if (!isValidStatusCode(method.getStatusCode())) {
        throw new UnknownHostException("Unable to obtain connection to " + httpUri + ". Returned status code "
                + method.getStatusCode());
    } else {
        // has a redirection been issued
        int numberOfRedirection = 0;
        while (isRedirected(method.getStatusCode()) && numberOfRedirection <= MAX_NO_REDIRECTS) {

            // release the existing connection
            method.releaseConnection();

            //attempt to follow the redirects
            numberOfRedirection++;

            // obtain the new location
            header = method.getResponseHeader("location");
            if (header != null) {
                try {
                    initialiseSettings(new URL(header.getValue()));
                    if (logger.isInfoEnabled()) {
                        logger.info("Redirecting to " + header.getValue());
                    }

                    // attempt a new connection to this location
                    method = getConnectionMethod(methodType);
                    connection.open();
                    method.execute(state, connection);
                    if (!isValidStatusCode(method.getStatusCode())) {
                        throw new UnknownHostException(
                                "Unable to obtain connection to " + " the redirected site " + httpUri
                                        + ". Returned status code " + method.getStatusCode());
                    }
                } catch (URISyntaxException ex) {
                    throw new IOException(
                            "Unable to follow redirection to " + header.getValue() + " Not a valid URI");
                }
            } else {
                throw new IOException("Unable to obtain redirecting detaild from " + httpUri);
            }
        }
    }

    // Update metadata about the cached document
    Header lastModifiedHeader = method.getResponseHeader("Last-Modified");
    if (lastModifiedHeader != null) {
        logger.debug(lastModifiedHeader.toString());
        assert lastModifiedHeader.getElements().length >= 1;
        assert lastModifiedHeader.getElements()[0].getName() != null;
        assert lastModifiedHeader.getElements()[0].getName() instanceof String;
        // previous code: added to cache
    }

    Header eTagHeader = method.getResponseHeader("Etag");
    if (eTagHeader != null) {
        logger.debug(eTagHeader.toString());
        assert eTagHeader.getElements().length >= 1;
        assert eTagHeader.getElements()[0].getName() != null;
        assert eTagHeader.getElements()[0].getName() instanceof String;
        // previous code: added to cache
    }

    return method;
}

From source file:org.mulgara.resolver.http.HttpContent.java

/**
 * Read the mime type. Should only be done if the Mime type is not already available
 * as this will close the connection./*w ww  . j  a v  a 2  s .  c  o m*/
 * @return The MimeType for the URL.
 * @throws NotModifiedException if the content validates against the cache
 */
@SuppressWarnings("unchecked")
private MimeType readMimeType(HttpMethod method) throws NotModifiedException {
    MimeType result = null;
    String contentType = null;

    try {
        // obtain connection and retrieve the headers
        Header header = method.getResponseHeader("Content-Type");
        if (header != null) {
            contentType = header.getValue();
            // find the parameter separator so we can protect against bad params
            int sep = contentType.indexOf(';');
            // no params, just create the MimeType
            if (sep < 0)
                result = new MimeType(contentType);
            else {
                // create the MimeType from the type/subtype
                result = new MimeType(contentType.substring(0, sep));
                // parse parameters separately and set the result accordingly
                try {
                    MimeTypeParameterList params = new MimeTypeParameterList(contentType.substring(sep + 1));
                    Enumeration<String> names = (Enumeration<String>) params.getNames();
                    while (names.hasMoreElements()) {
                        String name = names.nextElement();
                        result.setParameter(name, params.get(name));
                    }
                } catch (MimeTypeParseException e) {
                    logger.warn("Ignoring bad parameters in '" + contentType.substring(sep + 1)
                            + "' from the content type for " + httpUri);
                }
            }
            if (logger.isInfoEnabled()) {
                logger.info("Obtain content type " + result + "  from " + httpUri);
            }
        }
    } catch (java.lang.IllegalStateException e) {
        logger.info("Unable to obtain content type for " + httpUri);
    } catch (MimeTypeParseException e) {
        logger.warn("Unexpected parameters before ; in '" + contentType + "' as a content type for " + httpUri);
    }
    return result;
}

From source file:org.nunux.poc.portal.ProxyServlet.java

/**
 * Executes the {@link HttpMethod} passed in and sends the proxy response
 * back to the client via the given {@link HttpServletResponse}
 *
 * @param httpMethodProxyRequest An object representing the proxy request to
 * be made/*  w w w. j av a2 s .c o  m*/
 * @param httpServletResponse An object by which we can send the proxied
 * response back to the client
 * @throws IOException Can be thrown by the {@link HttpClient}.executeMethod
 * @throws ServletException Can be thrown to indicate that another error has
 * occurred
 */
private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws IOException, ServletException {

    if (httpServletRequest.isSecure()) {
        Protocol.registerProtocol("https", new Protocol("https", new EasySSLProtocolSocketFactory(), 443));
    }

    // Create a default HttpClient
    HttpClient httpClient = new HttpClient();
    httpMethodProxyRequest.setFollowRedirects(false);
    // Execute the request
    int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest);
    InputStream response = httpMethodProxyRequest.getResponseBodyAsStream();

    // 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();
        if (followRedirects) {
            if (stringLocation.contains("jsessionid")) {
                Cookie cookie = new Cookie("JSESSIONID",
                        stringLocation.substring(stringLocation.indexOf("jsessionid=") + 11));
                cookie.setPath("/");
                httpServletResponse.addCookie(cookie);
                //debug("redirecting: set jessionid (" + cookie.getValue() + ") cookie from URL");
            } else if (httpMethodProxyRequest.getResponseHeader("Set-Cookie") != null) {
                Header header = httpMethodProxyRequest.getResponseHeader("Set-Cookie");
                String[] cookieDetails = header.getValue().split(";");
                String[] nameValue = cookieDetails[0].split("=");

                if (nameValue[0].equalsIgnoreCase("jsessionid")) {
                    httpServletRequest.getSession().setAttribute("jsessionid" + this.getProxyHostAndPort(),
                            nameValue[1]);
                    debug("redirecting: store jsessionid: " + nameValue[1]);
                } else {
                    Cookie cookie = new Cookie(nameValue[0], nameValue[1]);
                    cookie.setPath("/");
                    //debug("redirecting: setting cookie: " + cookie.getName() + ":" + cookie.getValue() + " on " + cookie.getPath());
                    httpServletResponse.addCookie(cookie);
                }
            }
            httpServletResponse.sendRedirect(
                    stringLocation.replace(getProxyHostAndPort() + this.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 (header.getName().equals("Transfer-Encoding") && header.getValue().equals("chunked")
                || header.getName().equals("Content-Encoding") && header.getValue().equals("gzip") || // don't copy gzip header
                header.getName().equals("WWW-Authenticate")) { // don't copy WWW-Authenticate header so browser doesn't prompt on failed basic auth
            // proxy servlet does not support chunked encoding
        } else if (header.getName().equals("Set-Cookie")) {
            String[] cookieDetails = header.getValue().split(";");
            String[] nameValue = cookieDetails[0].split("=");
            if (nameValue[0].equalsIgnoreCase("jsessionid")) {
                httpServletRequest.getSession().setAttribute("jsessionid" + this.getProxyHostAndPort(),
                        nameValue[1]);
                debug("redirecting: store jsessionid: " + nameValue[1]);
            } else {
                httpServletResponse.setHeader(header.getName(), header.getValue());
            }
        } else {
            httpServletResponse.setHeader(header.getName(), header.getValue());
        }
    }

    List<Header> responseHeaders = Arrays.asList(headerArrayResponse);

    if (isBodyParameterGzipped(responseHeaders)) {
        debug("GZipped: true");
        int length = 0;

        if (!followRedirects && intProxyResponseCode == HttpServletResponse.SC_MOVED_TEMPORARILY) {
            String gz = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            intProxyResponseCode = HttpServletResponse.SC_OK;
            httpServletResponse.setHeader(STRING_LOCATION_HEADER, gz);
        } else {
            final byte[] bytes = ungzip(httpMethodProxyRequest.getResponseBody());
            length = bytes.length;
            response = new ByteArrayInputStream(bytes);
        }
        httpServletResponse.setContentLength(length);
    }

    // Send the content to the client
    debug("Received status code: " + intProxyResponseCode, "Response: " + response);

    //httpServletResponse.getWriter().write(response);
    copy(response, httpServletResponse.getOutputStream());
}

From source file:org.nuxeo.opensocial.shindig.gadgets.NXHttpFetcher.java

/** {@inheritDoc} */
public HttpResponse fetch(HttpRequest request) {
    HttpClient httpClient = new HttpClient();
    HttpMethod httpMethod;
    String methodType = request.getMethod();
    String requestUri = request.getUri().toString();

    ProxyHelper.fillProxy(httpClient, requestUri);

    // true for non-HEAD requests
    boolean requestCompressedContent = true;

    if ("POST".equals(methodType) || "PUT".equals(methodType)) {
        EntityEnclosingMethod enclosingMethod = ("POST".equals(methodType)) ? new PostMethod(requestUri)
                : new PutMethod(requestUri);

        if (request.getPostBodyLength() > 0) {
            enclosingMethod.setRequestEntity(new InputStreamRequestEntity(request.getPostBody()));
            enclosingMethod.setRequestHeader("Content-Length", String.valueOf(request.getPostBodyLength()));
        }// ww w . j ava 2 s  .c  o  m
        httpMethod = enclosingMethod;
    } else if ("DELETE".equals(methodType)) {
        httpMethod = new DeleteMethod(requestUri);
    } else if ("HEAD".equals(methodType)) {
        httpMethod = new HeadMethod(requestUri);
    } else {
        httpMethod = new GetMethod(requestUri);
    }

    httpMethod.setFollowRedirects(false);
    httpMethod.getParams().setSoTimeout(connectionTimeoutMs);

    if (requestCompressedContent)
        httpMethod.setRequestHeader("Accept-Encoding", "gzip, deflate");

    for (Map.Entry<String, List<String>> entry : request.getHeaders().entrySet()) {
        httpMethod.setRequestHeader(entry.getKey(), StringUtils.join(entry.getValue(), ','));
    }

    try {

        int statusCode = httpClient.executeMethod(httpMethod);

        // Handle redirects manually
        if (request.getFollowRedirects() && ((statusCode == HttpStatus.SC_MOVED_TEMPORARILY)
                || (statusCode == HttpStatus.SC_MOVED_PERMANENTLY) || (statusCode == HttpStatus.SC_SEE_OTHER)
                || (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT))) {

            Header header = httpMethod.getResponseHeader("location");
            if (header != null) {
                String redirectUri = header.getValue();

                if ((redirectUri == null) || (redirectUri.equals(""))) {
                    redirectUri = "/";
                }
                httpMethod.releaseConnection();
                httpMethod = new GetMethod(redirectUri);

                statusCode = httpClient.executeMethod(httpMethod);
            }
        }

        return makeResponse(httpMethod, statusCode);

    } catch (IOException e) {
        if (e instanceof java.net.SocketTimeoutException || e instanceof java.net.SocketException) {
            return HttpResponse.timeout();
        }

        return HttpResponse.error();

    } finally {
        httpMethod.releaseConnection();
    }
}

From source file:org.olat.core.commons.modules.glossary.morphService.MorphologicalServiceDEImpl.java

private InputStream retreiveXMLReply(String partOfSpeech, String word) {
    HttpClient client = HttpClientFactory.getHttpClientInstance();
    HttpMethod method = new GetMethod(MORPHOLOGICAL_SERVICE_ADRESS);
    NameValuePair posValues = new NameValuePair(PART_OF_SPEECH_PARAM, partOfSpeech);
    NameValuePair wordValues = new NameValuePair(GLOSS_TERM_PARAM, word);
    if (log.isDebug()) {
        String url = MORPHOLOGICAL_SERVICE_ADRESS + "?" + PART_OF_SPEECH_PARAM + "=" + partOfSpeech + "&"
                + GLOSS_TERM_PARAM + "=" + word;
        log.debug("Send GET request to morph-service with URL: " + url);
    }/*from w  ww  .ja v  a2  s  .c o  m*/
    method.setQueryString(new NameValuePair[] { posValues, wordValues });
    try {
        client.executeMethod(method);
        int status = method.getStatusCode();
        if (status == HttpStatus.SC_NOT_MODIFIED || status == HttpStatus.SC_OK) {
            if (log.isDebug()) {
                log.debug("got a valid reply!");
            }
        } else if (method.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            log.error("Morphological Service unavailable (404)::" + method.getStatusLine().toString());
        } else {
            log.error("Unexpected HTTP Status::" + method.getStatusLine().toString());
        }
    } catch (Exception e) {
        log.error("Unexpected exception trying to get flexions!", e);
    }
    Header responseHeader = method.getResponseHeader("Content-Type");
    if (responseHeader == null) {
        // error
        log.error("URL not found!");
    }
    HttpRequestMediaResource mr = new HttpRequestMediaResource(method);
    InputStream inputStream = mr.getInputStream();

    return inputStream;
}