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.codeartisans.proxilet.Proxilet.java

/**
 * Executes the {@link HttpMethod} passed in and sends the proxy response back to the client via the given
 * {@link HttpServletResponse}.//from w w  w  .  j  av  a 2  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 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 {
    // Create a default HttpClient
    HttpClient httpClient;
    httpClient = createClientWithLogin();
    httpMethodProxyRequest.setFollowRedirects(false);

    // Execute the request
    int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest);
    //        String response = httpMethodProxyRequest.getResponseBodyAsString();

    // 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(HEADER_LOCATION).getValue();
        if (stringLocation == null) {
            throw new ServletException("Received status code: " + stringStatusCode + " but no "
                    + HEADER_LOCATION + " 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) {
            httpServletResponse
                    .sendRedirect(stringLocation.replace(getProxyHostAndPort() + proxyPath, 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(HEADER_CONTENT_LENGTH, 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")) {
            // proxy servlet does not support chunked encoding
        } else {
            httpServletResponse.setHeader(header.getName(), header.getValue());
        }
    }

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

    // FIXME We should handle both String and bytes response in the same way:
    String response = null;
    byte[] bodyBytes = null;

    if (isBodyParameterGzipped(responseHeaders)) {
        LOGGER.trace("GZipped: true");
        if (!followRedirects && intProxyResponseCode == HttpServletResponse.SC_MOVED_TEMPORARILY) {
            response = httpMethodProxyRequest.getResponseHeader(HEADER_LOCATION).getValue();
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            intProxyResponseCode = HttpServletResponse.SC_OK;
            httpServletResponse.setHeader(HEADER_LOCATION, response);
            httpServletResponse.setContentLength(response.length());
        } else {
            bodyBytes = ungzip(httpMethodProxyRequest.getResponseBody());
            httpServletResponse.setContentLength(bodyBytes.length);
        }
    }

    if (httpServletResponse.getContentType() != null && httpServletResponse.getContentType().contains("text")) {
        LOGGER.trace("Received status code: {} Response: {}", intProxyResponseCode, response);
    } else {
        LOGGER.trace("Received status code: {} [Response is not textual]", intProxyResponseCode);
    }

    // Send the content to the client
    if (response != null) {
        httpServletResponse.getWriter().write(response);
    } else if (bodyBytes != null) {
        httpServletResponse.getOutputStream().write(bodyBytes);
    } else {
        IOUtils.copy(httpMethodProxyRequest.getResponseBodyAsStream(), httpServletResponse.getOutputStream());
    }
}

From source file:org.collectionspace.chain.csp.persistence.services.connection.ReturnedDocument.java

public void setResponse(HttpMethod method, int status) throws IOException, DocumentException {
    this.status = status;
    InputStream stream = method.getResponseBodyAsStream();
    SAXReader reader = new SAXReader();
    if (status >= 400) {
        log.error("Got error : " + IOUtils.toString(stream));
    }/*from  w  ww . j  a  v  a2  s.c o  m*/
    // TODO errorhandling
    Document out = null;
    Header content_type = method.getResponseHeader("Content-Type");
    if (content_type != null && "application/xml".equals(content_type.getValue())) {
        if (log.isDebugEnabled()) {
            ByteArrayOutputStream dump = new ByteArrayOutputStream();
            // TODO CSPACE-2552 add ,"UTF-8" to reader.read()?
            out = reader.read(new TeeInputStream(stream, dump));
            log.debug(dump.toString("UTF-8"));
        } else {
            // TODO CSPACE-2552 add ,"UTF-8" to reader.read()?
            out = reader.read(stream);
        }
    }
    stream.close();
    doc = out;
}

From source file:org.collectionspace.chain.csp.persistence.services.connection.ReturnedMultipartDocument.java

public void setResponse(HttpMethod method, int status) throws Exception {
    setStatus(status);//from w w w  .ja v  a 2s.  c o  m
    InputStream stream = method.getResponseBodyAsStream();
    SAXReader reader = new SAXReader();
    if (isErrorStatus()) {
        log.info("Got error : " + IOUtils.toString(stream));
    }
    // TODO errorhandling
    Document doc = null;
    Header content_type = method.getResponseHeader("Content-Type");
    if (content_type != null && "application/xml".equals(content_type.getValue())) {

        if (log.isDebugEnabled()) {
            ByteArrayOutputStream dump = new ByteArrayOutputStream();
            doc = reader.read(new TeeInputStream(stream, dump));
            log.debug(dump.toString("UTF-8"));
        } else {
            doc = reader.read(stream, "UTF-8");
        }
        //split up document
        Element root = doc.getRootElement();
        // iterate through child elements of root
        for (Iterator i = root.elementIterator(); i.hasNext();) {
            Element element = (Element) i.next();
            addDocument(element.getName(), DocumentHelper.parseText(element.asXML()));
        }
    }
    stream.close();
}

From source file:org.collectionspace.chain.csp.persistence.services.connection.ReturnedURL.java

public void setResponse(HttpMethod method, int status) throws Exception {
    String possiblemessg = method.getResponseBodyAsString();
    Header location = method.getResponseHeader("Location");
    if (location == null) {
        if (possiblemessg != "") {
            throw new ConnectionException(possiblemessg, status, "");
        }//from ww  w  . j  av a2 s  .co  m
        throw new ConnectionException("Missing location header " + method.getResponseBodyAsString(), status,
                "");
    }
    url = location.getValue();
    this.status = status;
}

From source file:org.deegree.portal.cataloguemanager.control.LoadOWSCapabilitiesListener.java

public void actionPerformed(WebEvent event, ResponseHandler responseHandler) throws IOException {
    String url = (String) event.getParameter().get("url");
    String version = (String) event.getParameter().get("version");
    String type = (String) event.getParameter().get("type");
    String req = "request=GetCapabilities&service=" + type;
    if (version != null && version.trim().length() > 0) {
        req += ("&version=" + version);
    }/*  w w w. j ava2 s.c o  m*/
    LOG.logInfo("URL: ", url);
    LOG.logInfo("request: ", req);

    HttpMethod get = HttpUtils.performHttpGet(url, req, 60000, null, null, null);

    // check if correct content type
    String contentType = get.getResponseHeader("Content-Type").getValue();
    if (!contentType.contains("xml")) {
        String msg = "Error: Response Content is " + contentType + " not xml";
        LOG.logError(msg);
        ExceptionBean bean = new ExceptionBean(this.getClass().getName(), msg);
        responseHandler.writeAndClose(true, bean);
        return;
    }

    session = event.getSession();
    InputStream is = get.getResponseBodyAsStream();
    try {
        if (type.equals("WMS")) {
            handleWMS(is, responseHandler);
        } else if (type.equals("WFS")) {
            handleWFS(is, responseHandler);
        } else if (type.equals("WCS")) {
            handleWCS(is, responseHandler);
        } else if (type.equals("CSW")) {
            handleCSW(is, responseHandler);
        } else {
            is.close();
            String msg = "unknow service type requested: " + url;
            LOG.logError(msg);
            ExceptionBean bean = new ExceptionBean(this.getClass().getName(), msg);
            responseHandler.writeAndClose(true, bean);
            return;
        }
    } catch (Exception e) {
        LOG.logError(e);
        ExceptionBean bean = new ExceptionBean(this.getClass().getName(), e.getMessage());
        responseHandler.writeAndClose(true, bean);
    }

}

From source file:org.eclipse.mylyn.internal.commons.xmlrpc.CommonXmlRpcClient.java

protected void createXmlRpcClient() {
    config = new XmlRpcClientConfigImpl();
    config.setEncoding(DEFAULT_CHARSET);
    config.setTimeZone(TimeZone.getTimeZone(DEFAULT_TIME_ZONE));
    config.setContentLengthOptional(false);
    config.setConnectionTimeout(WebUtil.getConnectionTimeout());
    config.setReplyTimeout(WebUtil.getSocketTimeout());

    xmlrpc = new XmlRpcClient();
    xmlrpc.setConfig(config);//w w w.j ava2 s .  com
    // bug 307200: force factory that supports proper UTF-8 encoding
    xmlrpc.setXmlWriterFactory(new CharSetXmlWriterFactory());

    factory = new HttpClientTransportFactory(xmlrpc, httpClient);
    factory.setLocation(location);
    factory.setInterceptor(new HttpMethodInterceptor() {
        public void processRequest(HttpMethod method) {
            DigestScheme scheme = digestScheme;
            if (scheme != null) {
                if (DEBUG_AUTH) {
                    System.err.println(location.getUrl() + ": Digest scheme is present"); //$NON-NLS-1$ 
                }
                Credentials creds = httpClient.getState().getCredentials(authScope);
                if (creds != null) {
                    if (DEBUG_AUTH) {
                        System.err.println(location.getUrl() + ": Setting digest scheme for request"); //$NON-NLS-1$ 
                    }
                    method.getHostAuthState().setAuthScheme(digestScheme);
                    method.getHostAuthState().setAuthRequested(true);
                }
            }
        }

        @SuppressWarnings("null")
        public void processResponse(HttpMethod method) throws XmlRpcException {
            if (isContentTypeCheckingEnabled()) {
                Header contentTypeHeader = method.getResponseHeader("Content-Type"); //$NON-NLS-1$
                if (contentTypeHeader == null || !DEFAULT_CONTENT_TYPE.equals(contentTypeHeader.getValue())) {
                    throw new XmlRpcIllegalContentTypeException(
                            NLS.bind("The server returned an unexpected content type: ''{0}''", //$NON-NLS-1$
                                    contentTypeHeader.getValue()),
                            contentTypeHeader.getValue());
                }
            }
            AuthScheme authScheme = method.getHostAuthState().getAuthScheme();
            if (authScheme instanceof DigestScheme) {
                digestScheme = (DigestScheme) authScheme;
                if (DEBUG_AUTH) {
                    System.err.println(location.getUrl() + ": Received digest scheme"); //$NON-NLS-1$ 
                }
            }
        }
    });
    xmlrpc.setTransportFactory(factory);

    try {
        config.setServerURL(new URL(location.getUrl()));
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.eclipse.mylyn.internal.jira.core.service.web.rss.JiraRssSessionCallback.java

/**
 * Determines if the response of <code>method</code> was GZip encoded
 * /*from   w w w  .j  av  a 2  s.c o m*/
 * @param method
 *            Method to determine encoding of
 * @return <code>true</code> if the resposne was GZip encoded, <code>false</code> otherwise.
 */
private boolean isResponseGZipped(HttpMethod method) {
    Header contentEncoding = method.getResponseHeader("Content-Encoding"); //$NON-NLS-1$
    return contentEncoding != null && "gzip".equals(contentEncoding.getValue()); //$NON-NLS-1$
}

From source file:org.eclipse.mylyn.internal.jira.core.service.web.rss.JiraRssSessionCallback.java

private boolean isXMLOrRSS(HttpMethod method) throws HttpException {
    Header contentType = method.getResponseHeader("Content-Type"); //$NON-NLS-1$
    if (contentType == null) {
        return false;
    }/*from   ww  w  .  j  a  va 2s . co m*/

    HeaderElement[] values = contentType.getElements();
    for (HeaderElement element : values) {
        if (element.getName().startsWith("text/xml")) { //$NON-NLS-1$
            return true;
        }
    }

    return false;
}

From source file:org.eclipse.mylyn.internal.web.tasks.WebRepositoryConnector.java

private static String getRefreshUrl(String url, HttpMethod method) {
    Header refreshHeader = method.getResponseHeader("Refresh"); //$NON-NLS-1$
    if (refreshHeader == null) {
        return null;
    }/*  www  . ja v a  2  s  .c  om*/
    String value = refreshHeader.getValue();
    int n = value.indexOf(";url="); //$NON-NLS-1$
    if (n == -1) {
        return null;
    }
    value = value.substring(n + 5);
    int requestPath;
    if (value.charAt(0) == '/') {
        int colonSlashSlash = url.indexOf("://"); //$NON-NLS-1$
        requestPath = url.indexOf('/', colonSlashSlash + 3);
    } else {
        requestPath = url.lastIndexOf('/');
    }

    String refreshUrl;
    if (requestPath == -1) {
        refreshUrl = url + "/" + value; //$NON-NLS-1$
    } else {
        refreshUrl = url.substring(0, requestPath + 1) + value;
    }
    return refreshUrl;
}

From source file:org.eclipse.om2m.comm.http.RestHttpClient.java

/**
* Converts a protocol-independent {@link RequestIndication} object into a standard HTTP request and sends a standard HTTP request.
* Converts the received standard HTTP request into {@link ResponseConfirm} object and returns it back.
* @param requestIndication - protocol independent request.
* @return protocol independent response.
*//*from   ww  w. j  a va  2 s  . com*/
public ResponseConfirm sendRequest(RequestIndication requestIndication) {

    logServiceTracker = new ServiceTracker(FrameworkUtil.getBundle(RestHttpClient.class).getBundleContext(),
            org.osgi.service.log.LogService.class.getName(), null);
    logServiceTracker.open();
    logservice = (LogService) logServiceTracker.getService();
    LOGGER.debug("Http Client > " + requestIndication);
    logservice.log(LogService.LOG_ERROR, "Http Client > " + requestIndication);

    HttpClient httpclient = new HttpClient();

    ResponseConfirm responseConfirm = new ResponseConfirm();
    HttpMethod httpMethod = null;
    String url = requestIndication.getUrl();
    if (!url.startsWith(protocol + "://")) {
        url = protocol + "://" + url;
    }
    try {
        switch (requestIndication.getMethod()) {
        case "RETRIEVE":
            httpMethod = new GetMethod(url);
            break;
        case "CREATE":
            httpMethod = new PostMethod(url);

            ((PostMethod) httpMethod).setRequestEntity(
                    new StringRequestEntity(requestIndication.getRepresentation(), "application/xml", "UTF8"));
            break;
        case "UPDATE":
            httpMethod = new PutMethod(url);
            ((PutMethod) httpMethod).setRequestEntity(
                    new StringRequestEntity(requestIndication.getRepresentation(), "application/xml", "UTF8"));
            break;
        case "DELETE":
            httpMethod = new DeleteMethod(url);
            break;
        case "EXECUTE":
            httpMethod = new PostMethod(url);
            break;
        default:
            return new ResponseConfirm();
        }
        httpMethod.addRequestHeader("Authorization",
                "Basic " + new String(Base64.encodeBase64(requestIndication.getRequestingEntity().getBytes())));
        httpMethod.setQueryString(getQueryFromParams(requestIndication.getParameters()));

        int statusCode = httpclient.executeMethod(httpMethod);
        responseConfirm.setStatusCode(getRestStatusCode(statusCode));

        if (statusCode != 204) {
            if (httpMethod.getResponseBody() != null) {
                responseConfirm.setRepresentation(new String(httpMethod.getResponseBody()));
            }
        }
        if (statusCode == 201) {
            if (httpMethod.getResponseHeader("Location").getValue() != null) {
                responseConfirm.setResourceURI(httpMethod.getResponseHeader("Location").getValue());
            }
        }
        //LOGGER.debug("Http Client > "+responseConfirm);
        LOGGER.debug("Http Client > " + responseConfirm);
        logservice.log(LogService.LOG_ERROR, "Http Client > " + responseConfirm);

    } catch (IOException e) {
        LOGGER.error(url + " Not Found" + responseConfirm, e);
        logservice.log(LogService.LOG_ERROR, url + " Not Found" + responseConfirm);

    } finally {
        httpMethod.releaseConnection();
    }

    return responseConfirm;
}