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

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

Introduction

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

Prototype

public abstract Header[] getResponseHeaders();

Source Link

Usage

From source file:org.chiba.xml.xforms.connector.http.AbstractHTTPConnector.java

protected void handleHttpMethod(HttpMethod httpMethod) throws Exception {
    Header[] headers = httpMethod.getResponseHeaders();
    this.responseHeader = new HashMap();

    for (int index = 0; index < headers.length; index++) {
        responseHeader.put(headers[index].getName(), headers[index].getValue());
    }//w  w w  .j  a  v a 2  s  .c om

    this.responseBody = httpMethod.getResponseBodyAsStream();
}

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  ww  .  j a v a2 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 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.codehaus.httpcache4j.client.HTTPClientResponseResolver.java

private HTTPResponse convertResponse(HttpMethod method) {
    Headers headers = new Headers();
    for (Header header : method.getResponseHeaders()) {
        headers = headers.add(header.getName(), header.getValue());
    }/*  w ww .j a v a 2  s.  c  o  m*/
    InputStream stream = null;
    HTTPResponse response;
    try {
        stream = getInputStream(method);
        StatusLine line = new StatusLine(HTTPVersion.get(method.getStatusLine().getHttpVersion()),
                Status.valueOf(method.getStatusCode()), method.getStatusText());
        response = getResponseCreator().createResponse(line, headers, stream);
    } finally {
        if (stream == null) {
            method.releaseConnection();
        }
    }
    return response;
}

From source file:org.codehaus.httpcache4j.client.HTTPClientResponseResolverTest.java

private HTTPClientResponseResolver createResponseResolver(final HttpMethod httpMethod, final Status status,
        final Header[] headers) {
    try {/*ww w .j  av a 2  s .c om*/
        when(httpMethod.getStatusLine()).thenReturn(new org.apache.commons.httpclient.StatusLine(
                String.format("HTTP/1.1 %s %s\r\n", status.getCode(), status.getName())));
    } catch (HttpException e) {
        throw new RuntimeException(e);
    }
    when(httpMethod.getStatusCode()).thenReturn(status.getCode());
    when(httpMethod.getResponseHeaders()).thenReturn(headers);
    return new TestableHTTPClientResponseResolver(httpMethod);
}

From source file:org.codehaus.wadi.web.impl.CommonsHttpProxy.java

protected void doProxy(URI uri, WebInvocation context) throws ProxyingException {
    HttpServletRequest hreq = context.getHreq();
    HttpServletResponse hres = context.getHres();

    long startTime = System.currentTimeMillis();

    String m = hreq.getMethod();/*  w  ww  .ja  va  2  s.  co  m*/
    Class clazz = (Class) _methods.get(m);
    if (clazz == null) {
        throw new IrrecoverableException("unsupported http method: " + m);
    }

    HttpMethod hm = null;
    try {
        hm = (HttpMethod) clazz.newInstance();
    } catch (Exception e) {
        throw new IrrecoverableException("could not create HttpMethod instance", e); // should never happen
    }

    String requestURI = getRequestURI(hreq);
    hm.setPath(requestURI);

    String queryString = hreq.getQueryString();
    if (queryString != null) {
        hm.setQueryString(queryString);
        requestURI += queryString;
    }

    hm.setFollowRedirects(false);
    //hm.setURI(new URI(uri));
    hm.setStrictMode(false);

    // check connection header
    String connectionHdr = hreq.getHeader("Connection"); // TODO - what if there are multiple values ?
    if (connectionHdr != null) {
        connectionHdr = connectionHdr.toLowerCase();
        if (connectionHdr.equals("keep-alive") || connectionHdr.equals("close"))
            connectionHdr = null; // TODO  ??
    }

    // copy headers
    boolean xForwardedFor = false;
    boolean hasContent = false;
    int contentLength = 0;
    Enumeration enm = hreq.getHeaderNames();
    while (enm.hasMoreElements()) {
        // TODO could be better than this! - using javax.servlet ?
        String hdr = (String) enm.nextElement();
        String lhdr = hdr.toLowerCase();

        if (_DontProxyHeaders.contains(lhdr))
            continue;
        if (connectionHdr != null && connectionHdr.indexOf(lhdr) >= 0)
            continue;

        if ("content-length".equals(lhdr)) {
            try {
                contentLength = hreq.getIntHeader(hdr);
                hasContent = contentLength > 0;
            } catch (NumberFormatException e) {
                if (_log.isWarnEnabled())
                    _log.warn("bad Content-Length header value: " + hreq.getHeader(hdr), e);
            }
        }

        if ("content-type".equals(lhdr)) {
            hasContent = true;
        }

        Enumeration vals = hreq.getHeaders(hdr);
        while (vals.hasMoreElements()) {
            String val = (String) vals.nextElement();
            if (val != null) {
                hm.addRequestHeader(hdr, val);
                // if (_log.isInfoEnabled()) _log.info("Request " + hdr + ": " + val);
                xForwardedFor |= "X-Forwarded-For".equalsIgnoreCase(hdr); // why is this not in the outer loop ?
            }
        }
    }

    // cookies...

    // although we copy cookie headers into the request abover - commons-httpclient thinks it knows better and strips them out before sending.
    // we have to explicitly use their interface to add the cookies - painful...

    // DOH! - an org.apache.commons.httpclient.Cookie is NOT a
    // javax.servlet.http.Cookie - and it looks like the two don't
    // map onto each other without data loss...
    HttpState state = new HttpState();
    javax.servlet.http.Cookie[] cookies = hreq.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            javax.servlet.http.Cookie c = cookies[i];
            String domain = c.getDomain();
            if (domain == null) {
                domain = hreq.getServerName(); // TODO - tmp test
                // _log.warn("defaulting cookie domain");
            }
            //     domain=null;
            String cpath = c.getPath();
            if (cpath == null) {
                cpath = hreq.getContextPath(); // fix for Jetty
                // _log.warn("defaulting cookie path");
            }
            //if (_log.isTraceEnabled()) _log.trace("PATH: value="+path+" length="+(path==null?0:path.length()));
            Cookie cookie = new Cookie(domain, c.getName(), c.getValue(), cpath, c.getMaxAge(), c.getSecure()); // TODO - sort out domain
            //if (_log.isTraceEnabled()) _log.trace("Cookie: "+cookie.getDomain()+","+ cookie.getName()+","+ cookie.getValue()+","+ cookie.getPath()+","+ cookie.getExpiryDate()+","+ cookie.getSecure());
            state.addCookie(cookie);
            //if (_log.isTraceEnabled()) _log.trace("Cookie: "+cookie.toString());
        }
    }

    // Proxy headers
    hm.addRequestHeader("Via", "1.1 " + hreq.getLocalName() + ":" + hreq.getLocalPort() + " \"WADI\"");
    if (!xForwardedFor)
        hm.addRequestHeader("X-Forwarded-For", hreq.getRemoteAddr());
    // Max-Forwards...

    // a little bit of cache control
    //      String cache_control = hreq.getHeader("Cache-Control");
    //      if (cache_control != null && (cache_control.indexOf("no-cache") >= 0 || cache_control.indexOf("no-store") >= 0))
    //      httpMethod.setUseCaches(false);

    // customize Connection
    //      uc.setDoInput(true);

    int client2ServerTotal = 0;
    if (hasContent) {
        //         uc.setDoOutput(true);

        try {
            if (hm instanceof EntityEnclosingMethod)
                ((EntityEnclosingMethod) hm).setRequestBody(hreq.getInputStream());
            // TODO - do we need to close response stream at end... ?
        } catch (IOException e) {
            throw new IrrecoverableException("could not pss request input across proxy", e);
        }
    }

    try {
        HttpClient client = new HttpClient();
        HostConfiguration hc = new HostConfiguration();
        //String host=location.getAddress().getHostAddress();
        // inefficient - but stops httpclient from rejecting half our cookies...
        String host = uri.getHost();
        hc.setHost(host, uri.getPort());
        client.executeMethod(hc, hm, state);
    } catch (IOException e) // TODO
    {
        _log.warn("problem proxying connection:", e);
    }

    InputStream fromServer = null;

    // handler status codes etc.
    int code = 502;
    //      String message="Bad Gateway: could not read server response code or message";

    code = hm.getStatusCode(); // IOException
    //      message=hm.getStatusText(); // IOException
    hres.setStatus(code);
    //      hres.setStatus(code, message); - deprecated...

    try {
        fromServer = hm.getResponseBodyAsStream(); // IOException
    } catch (IOException e) {
        _log.warn("problem acquiring http client output", e);
    }

    // clear response defaults.
    hres.setHeader("Date", null);
    hres.setHeader("Server", null);

    // set response headers
    // TODO - is it a bug in Jetty that I have to start my loop at 1 ? or that key[0]==null ?
    // Try this inside Tomcat...
    Header[] headers = hm.getResponseHeaders();
    for (int i = 0; i < headers.length; i++) {
        String h = headers[i].toExternalForm();
        int index = h.indexOf(':');
        String key = h.substring(0, index).trim().toLowerCase();
        String val = h.substring(index + 1, h.length()).trim();
        if (val != null && !_DontProxyHeaders.contains(key)) {
            hres.addHeader(key, val);
            // if (_log.isInfoEnabled()) _log.info("Response: "+key+" - "+val);
        }
    }

    hres.addHeader("Via", "1.1 (WADI)");

    // copy server->client
    int server2ClientTotal = 0;
    if (fromServer != null) {
        try {
            OutputStream toClient = hres.getOutputStream();// IOException
            server2ClientTotal += copy(fromServer, toClient, 8192);// IOException
        } catch (IOException e) {
            _log.warn("problem proxying server response back to client", e);
        } finally {
            try {
                fromServer.close();
            } catch (IOException e) {
                // well - we did our best...
                _log.warn("problem closing server response stream", e);
            }
        }
    }

    long endTime = System.currentTimeMillis();
    long elapsed = endTime - startTime;
    if (_log.isDebugEnabled()) {
        _log.debug("in:" + client2ServerTotal + ", out:" + server2ClientTotal + ", status:" + code + ", time:"
                + elapsed + ", uri:" + uri);
    }
}

From source file:org.cryptomator.frontend.webdav.WebDavServerTest.java

@Test
public void testGet() throws HttpException, IOException {
    final HttpClient client = new HttpClient();

    // write test content:
    final byte[] testContent = "hello world".getBytes();
    try (WritableFile w = fs.file("foo.txt").openWritable()) {
        w.write(ByteBuffer.wrap(testContent));
    }/*from   w ww. j  a  v a 2  s.  c  o  m*/

    // check get response body:
    final HttpMethod getMethod = new GetMethod(servletRoot + "/foo.txt");
    final int statusCode = client.executeMethod(getMethod);
    Assert.assertEquals(200, statusCode);
    Assert.assertThat(getMethod.getResponseHeaders(), hasItemInArray(new Header("Accept-Ranges", "bytes")));
    Assert.assertTrue(
            IOUtils.contentEquals(new ByteArrayInputStream(testContent), getMethod.getResponseBodyAsStream()));
    getMethod.releaseConnection();
}

From source file:org.deegree.ogcwebservices.wass.wss.operation.DoServiceHandler.java

/**
 * This method does the actual request to the secured service. It returns the response of the
 * secured service as an inputstream. It also replace the GetCapabilities request - responses
 * with the facadeurl given by the client.
 *
 * @param request// w  w  w . java 2  s.  c om
 *            send by the client a DoService Request.
 * @param securedService
 *            the service for which this wss is proxying, must be put in the deegreeparams of
 *            the configuration file.
 * @param requestedCharset
 *            this wss uses, also read from the deegreeparams in the configuration file.
 * @param timeout
 *            how long to wait for a response. Service dependable therefor also read from the
 *            deegreeparams in the config file.
 * @param securedServiceName
 *            the name of the service for which we are proxying -> config.
 * @return the http response of the secured service as an inputstream.
 * @throws DoServiceException
 *             if an error occurs wile sending the request or treating the response. see
 *             org.deegree.ogcwebservices.csw.manager.CatalogueHarvester#getNextMetadataRecord
 */
public DoServiceResponse sendRequest(DoService request, URL securedService, String requestedCharset,
        int timeout, String securedServiceName) throws DoServiceException {
    if (requestAllowed) {

        Header[] headers = null;
        InputStream body = null;
        Header[] footers = null;
        String proxyRequest = null;
        try {
            proxyRequest = URLDecoder.decode(request.getPayload(), CharsetUtils.getSystemCharset());
        } catch (UnsupportedEncodingException e) {
            LOG.logError(e.getMessage(), e);
            throw new DoServiceException(Messages.getMessage("WASS_ERROR_INTERNAL", "WSS"));
        }
        LOG.logDebug("encoded proxyrequest: " + request.getPayload() + "\ndecoded proxy: " + proxyRequest);
        String dcp = request.getDcp();
        HttpClient client = new HttpClient();
        client = WebUtils.enableProxyUsage(client, securedService);
        StringRequestEntity requestEntity = null;
        HttpClientParams params = client.getParams();
        params.setSoTimeout(timeout);
        HttpMethod requestMethod = null;
        try {
            String contentType = null;
            for (RequestParameter param : request.getRequestParameters()) {
                if (param.getId().toLowerCase().trim().contains("mime-type"))
                    contentType = param.getParameter();
            }
            requestEntity = new StringRequestEntity(proxyRequest, contentType, requestedCharset);
        } catch (UnsupportedEncodingException e1) {
            throw new DoServiceException(Messages.getMessage("WASS_ERROR_ENCODING_NOT_SUPPORTED", "WSS"));
        }
        if (dcp.equalsIgnoreCase("http_post")) {

            // the url to the service must be written in the deegreeparams in the configuration
            // xml
            requestMethod = new PostMethod(securedService.toExternalForm());
            ((PostMethod) requestMethod).setRequestEntity(requestEntity);
        } else if (dcp.equalsIgnoreCase("http_get")) {
            requestMethod = new GetMethod(securedService.toExternalForm());
            requestMethod.setQueryString(proxyRequest);
        } else {
            throw new DoServiceException(Messages.getMessage("WASS_ERROR_NOT_POST_OR_GET", "WSS"));
        }
        // getDataRequest
        try {
            // make header parameters of the requestParameters.
            for (RequestParameter param : request.getRequestParameters()) {
                if (!param.getId().toLowerCase().trim().contains("mime-type"))// Contenttype
                    requestMethod.addRequestHeader(param.getId(), param.getParameter());
            }
            // Call the secured service
            client.executeMethod(requestMethod);
            headers = requestMethod.getResponseHeaders();
            footers = requestMethod.getResponseFooters();
            body = requestMethod.getResponseBodyAsStream();

            if (body == null)
                throw new DoServiceException(Messages.getMessage("WASS_ERROR_GOT_NO_RESPONSE", "WSS"));
        } catch (HttpException e) {
            LOG.logError(e.getMessage(), e);
            throw new DoServiceException(Messages.getMessage("WASS_ERROR_EXCEPTION_IN_RESPONSE", "WSS"));
        } catch (IOException e) {
            LOG.logError(e.getMessage(), e);
            throw new DoServiceException(Messages.getMessage("WASS_ERROR_IN_TRANSPORT", "WSS"));
        }
        try {
            // Replace the given urls with the facadeurls if it is a GetCapabilities request
            if (proxyRequest.trim().contains("GetCapabilities")) {
                Operation[] operations = null;
                OGCCapabilitiesDocument doc = null;
                /*
                 * For now just check these service, others may be "secured" in the future.
                 */
                if ("WFS".equals(securedServiceName)) {
                    doc = new WFSCapabilitiesDocument();
                    doc.load(body, securedService.toExternalForm());
                    WFSCapabilities cap = (WFSCapabilities) doc.parseCapabilities();
                    operations = cap.getOperationsMetadata().getOperations();
                    replaceFacadeURL(operations, request.getFacadeURL());
                    doc = org.deegree.ogcwebservices.wfs.XMLFactory.export(cap);
                } else if (("WMS").equals(securedServiceName)) {
                    doc = new WMSCapabilitiesDocument();
                    doc.load(body, securedService.toExternalForm());
                    doc = WMSCapabilitiesDocumentFactory.getWMSCapabilitiesDocument(doc.getRootElement());
                    WMSCapabilities cap = (WMSCapabilities) doc.parseCapabilities();
                    org.deegree.owscommon_new.Operation[] ops = cap.getOperationMetadata().getOperations()
                            .toArray(new org.deegree.owscommon_new.Operation[0]);
                    replaceFacadeURL(ops, request.getFacadeURL());
                    doc = org.deegree.ogcwebservices.wms.XMLFactory.export(cap);
                } else if (("WCS").equals(securedServiceName)) {
                    doc = new WCSCapabilitiesDocument();
                    doc.load(body, securedService.toExternalForm());
                    WCSCapabilities cap = (WCSCapabilities) doc.parseCapabilities();
                    operations = cap.getCapabilitiy().getOperations().getOperations();
                    replaceFacadeURL(operations, request.getFacadeURL());
                    doc = org.deegree.ogcwebservices.wcs.XMLFactory.export(cap);
                } else if (("CSW").equals(securedServiceName)) {
                    doc = new CatalogueCapabilitiesDocument();
                    doc.load(body, securedService.toExternalForm());
                    CatalogueCapabilities cap = (CatalogueCapabilities) doc.parseCapabilities();
                    operations = cap.getOperationsMetadata().getOperations();
                    replaceFacadeURL(operations, request.getFacadeURL());
                    doc = org.deegree.ogcwebservices.csw.XMLFactory_2_0_0.export(cap, null);
                }

                body = new ByteArrayInputStream(doc.getAsString().getBytes());
            }
        } catch (IOException e) {
            LOG.logError(e.getMessage(), e);
            throw new DoServiceException(Messages.getMessage("WASS_ERROR_READING_BODY", "WSS"));
        } catch (InvalidCapabilitiesException e) {
            LOG.logError(e.getMessage(), e);
            throw new DoServiceException(Messages.getMessage("WASS_ERROR_CAPABILITIES_RESPONSE", "WSS"));
        } catch (SAXException e) {
            LOG.logError(e.getMessage(), e);
            throw new DoServiceException(Messages.getMessage("WASS_ERROR_FACADE_URL", "WSS"));
        } catch (XMLParsingException e) {
            LOG.logError(e.getMessage(), e);
            throw new DoServiceException(Messages.getMessage("WASS_ERROR_READING_BODY", "WSS"));
        }
        return new DoServiceResponse(headers, body, footers);
    }

    return null;
}

From source file:org.eclipse.ecf.remoteservice.rest.client.RestClientService.java

/**
 * Calls the Rest service with given URL of IRestCall. The returned value is
 * the response body as an InputStream.//from  www  . j a  v  a 2  s.c  om
 * 
 * @param call
 *            The remote call to make.  Must not be <code>null</code>.
 * @param callable
 *            The callable with default parameters to use to make the call.
 * @return The InputStream of the response body or <code>null</code> if an
 *         error occurs.
 */
protected Object invokeRemoteCall(final IRemoteCall call, final IRemoteCallable callable) throws ECFException {
    String uri = prepareEndpointAddress(call, callable);
    HttpMethod httpMethod = createAndPrepareHttpMethod(uri, call, callable);
    // execute method
    String responseBody = null;
    int responseCode = -1;
    try {
        responseCode = httpClient.executeMethod(httpMethod);
        if (isResponseOk(responseCode)) {
            // Get responseBody as String
            responseBody = getResponseAsString(httpMethod);
        } else {
            // If this method returns true, we should retrieve the response body
            if (retrieveErrorResponseBody(responseCode)) {
                responseBody = getResponseAsString(httpMethod);
            }
            // Now pass to the exception handler
            handleException("Http response not OK.  URL=" + uri + " responseCode=" + new Integer(responseCode), //$NON-NLS-1$//$NON-NLS-2$
                    null, responseCode, responseBody);
        }
    } catch (HttpException e) {
        handleException("Transport HttpException", e, responseCode); //$NON-NLS-1$
    } catch (IOException e) {
        handleException("Transport IOException", e, responseCode); //$NON-NLS-1$
    }
    Object result = null;
    try {
        result = processResponse(uri, call, callable, convertResponseHeaders(httpMethod.getResponseHeaders()),
                responseBody);
    } catch (NotSerializableException e) {
        handleException(
                "Exception deserializing response.  URL=" + uri + " responseCode=" + new Integer(responseCode), //$NON-NLS-1$//$NON-NLS-2$
                e, responseCode);
    }
    return result;
}

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

/**
 * Takes the HTTP Response and encodes it as an XML structure.
 *
 * @param   context     The context of the calling XQuery
 * @param   method      The HTTP Request Method
 * @param   statusCode  The status code returned from the http method invocation
 *
 * @return  The data in XML format//from w ww .j  av  a 2s.  c  o  m
 *
 * @throws  XPathException 
 * @throws  IOException     
 */
private Sequence encodeResponseAsXML(final XQueryContext context, final HttpMethod method, final int statusCode,
        final Map<String, Boolean> parserFeatures, final Map<String, String> parserProperties)
        throws XPathException, IOException {

    final MemTreeBuilder builder = context.getDocumentBuilder();

    builder.startDocument();
    builder.startElement(new QName("response", NAMESPACE_URI, PREFIX), null);
    builder.addAttribute(new QName("statusCode", null, null), String.valueOf(statusCode));

    //Add all the response headers
    builder.startElement(new QName("headers", NAMESPACE_URI, PREFIX), null);

    final NameValuePair[] headers = method.getResponseHeaders();

    for (final NameValuePair header : headers) {
        builder.startElement(new QName("header", NAMESPACE_URI, PREFIX), null);
        builder.addAttribute(new QName("name", null, null), header.getName());
        builder.addAttribute(new QName("value", null, null), header.getValue());
        builder.endElement();
    }

    builder.endElement();

    if (!(method instanceof HeadMethod || method instanceof OptionsMethod)) { // Head and Options methods never have any response body

        // Add the response body node
        builder.startElement(new QName("body", NAMESPACE_URI, PREFIX), null);

        insertResponseBody(context, method, builder, parserFeatures, parserProperties);

        builder.endElement();
    }

    builder.endElement();

    final Sequence xmlResponse = (NodeValue) builder.getDocument().getDocumentElement();
    return xmlResponse;
}

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

public final int prepareInvoke(HttpClient client, HttpMethod method, ProxyRequest request) throws Exception {
    // filer pre processing
    for (int i = 0; i < filterChain.size(); i++) {
        ProxyFilter filter = (ProxyFilter) filterChain.get(i);
        try {//from w  w w .  ja  v  a2  s . c  o m
            int statusCode = filter.preProcess(client, method, request);
            Header[] headers = method.getResponseHeaders();
            for (int j = 0; j < headers.length; j++) {
                request.putResponseHeader(headers[j].getName(), headers[j].getValue());
            }
            if (statusCode > 0) {
                return statusCode;
            }
        } catch (Exception e) {
            log.error("Throw exception from preProcess method.", e);
            return 500;
        }
    }
    return 0;
}