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:eu.delving.services.controller.SolrProxyController.java

@RequestMapping("/api/solr/select")
public void searchController(HttpServletRequest request, HttpServletResponse response) throws Exception {
    final String solrQueryString = request.getQueryString();
    HttpMethod method = new GetMethod(
            String.format("%s/select?%s", ThemeFilter.getTheme().getSolrSelectUrl(), solrQueryString));
    httpClient.executeMethod(method);/*from   w w w.j a  v  a2s.  com*/
    Boolean getAsStream = false;
    for (Header header : method.getResponseHeaders()) {
        if (header.getName().equalsIgnoreCase("content-type")) {
            final String contentType = method.getResponseHeader("Content-Type").getValue();
            response.setContentType(contentType);
            response.setHeader(header.getName(), header.getValue());
            if (contentType.equalsIgnoreCase("application/octet-stream")) {
                getAsStream = true;
            }
        } else if (header.getName().equalsIgnoreCase("server")) {
            //ignore
        } else {
            response.setHeader(header.getName(), header.getValue());
        }
    }
    response.setCharacterEncoding("UTF-8");
    if (getAsStream) {
        OutputStream out = response.getOutputStream();
        try {
            IOUtils.copy(method.getResponseBodyAsStream(), out);
        } finally {
            out.close();
        }
    } else {
        response.getWriter().write(method.getResponseBodyAsString()); //todo add response from SolrProxy here
        response.getWriter().close();
    }
}

From source file:com.feilong.tools.net.httpclient3.HttpClientUtil.java

/**
 * ?log./* w w w  .j a  v  a  2  s  . c  o  m*/
 *
 * @param httpMethod
 *            the http method
 * @param httpClientConfig
 *            the http client config
 * @return the http method response attribute map for log
 */
private static Map<String, Object> getHttpMethodResponseAttributeMapForLog(HttpMethod httpMethod,
        HttpClientConfig httpClientConfig) {
    Map<String, Object> map = new LinkedHashMap<String, Object>();

    Object statusCode = null;
    try {
        statusCode = httpMethod.getStatusCode();
    } catch (Exception e) {
        statusCode = e.getClass().getName() + " " + e.getMessage();
    }

    String statusText = null;
    try {
        statusText = httpMethod.getStatusText();
    } catch (Exception e) {
        statusText = e.getClass().getName() + " " + e.getMessage();
    }

    map.put("httpMethod.getRequestHeaders()-->map", NameValuePairUtil.toMap(httpMethod.getRequestHeaders()));

    map.put("httpMethod.getStatusCode()", statusCode);
    map.put("httpMethod.getStatusText()", statusText);
    map.put("httpMethod.getStatusLine()", "" + httpMethod.getStatusLine());

    map.put("httpMethod.getResponseHeaders()-->map", NameValuePairUtil.toMap(httpMethod.getResponseHeaders()));

    map.put("httpMethod.getResponseFooters()", httpMethod.getResponseFooters());
    map.put("httpClientConfig", httpClientConfig);

    return map;
}

From source file:com.sun.jersey.client.apache.ApacheHttpClientHandler.java

private InBoundHeaders getInBoundHeaders(HttpMethod method) {
    InBoundHeaders headers = new InBoundHeaders();
    Header[] respHeaders = method.getResponseHeaders();
    for (Header header : respHeaders) {
        List<String> list = headers.get(header.getName());
        if (list == null) {
            list = new ArrayList<String>();
        }/*w w w  . j a va 2s . com*/
        list.add(header.getValue());
        headers.put(header.getName(), list);
    }
    return headers;
}

From source file:ar.com.zauber.commons.web.proxy.HttpClientRequestProxy.java

/**
 * Pasa los headers de un request a otro. Copia todos salvo algunos
 * prohibidos que no tienen sentido./*from  w  ww  .  ja va2 s .c  o  m*/
 */
private void proxyHeaders(final HttpServletResponse response, final HttpMethod method) {
    final Header[] headers = method.getResponseHeaders();

    for (final Header header : headers) {
        boolean skip = false;
        for (final String forbidden : forbiddenHeader) {
            skip = header.getName().toLowerCase().equals(forbidden);
            if (skip) {
                break;
            }
        }

        if (!skip) {
            response.setHeader(header.getName(), header.getValue());
        }
    }
}

From source file:io.hops.hopsworks.api.admin.HDFSUIProxyServlet.java

protected void copyResponseHeaders(HttpMethod method, HttpServletRequest servletRequest,
        HttpServletResponse servletResponse) {
    for (org.apache.commons.httpclient.Header header : method.getResponseHeaders()) {
        if (hopByHopHeaders.containsHeader(header.getName())) {
            continue;
        }/*from  ww  w  . ja v  a 2  s.  c  om*/
        if (header.getName().equalsIgnoreCase("Content-Length")
                && (method.getResponseHeader("Content-Type") == null
                        || method.getResponseHeader("Content-Type").getValue().contains("html"))) {
            continue;
        }
        if (header.getName().equalsIgnoreCase(org.apache.http.cookie.SM.SET_COOKIE)
                || header.getName().equalsIgnoreCase(org.apache.http.cookie.SM.SET_COOKIE2)) {
            copyProxyCookie(servletRequest, servletResponse, header.getValue());
        } else {
            servletResponse.addHeader(header.getName(), header.getValue());
        }
    }
}

From source file:com.zimbra.cs.dav.client.WebDavClient.java

private void logResponseInfo(HttpMethod method) throws IOException {
    if (!mDebugEnabled) {
        return;/*  ww w  . ja  v  a  2  s.  c om*/
    }
    StringBuilder responseLog = new StringBuilder();
    responseLog.append("WebDAV response:\n").append(method.getStatusLine()).append('\n');
    Header headers[] = method.getResponseHeaders();
    if (headers != null && headers.length > 0) {
        for (Header hdr : headers) {
            String hdrName = hdr.getName();
            responseLog.append(hdrName).append('=');
            if (hdrName.contains("Auth") || (hdrName.contains(HttpHeaders.COOKIE))) {
                responseLog.append("*** REPLACED ***\n");
            } else {
                responseLog.append(hdr.getValue()).append('\n');
            }
        }
    }
    if (method.getResponseBody() == null || !ZimbraLog.dav.isTraceEnabled()) {
        ZimbraLog.dav.debug(responseLog.toString());
    } else {
        ZimbraLog.dav.debug("%s\n%s", responseLog.toString(), new String(method.getResponseBody(), "UTF-8"));
    }
}

From source file:gov.loc.ndmso.proxyfilter.RequestProxy.java

/**
 * This method performs the proxying of the request to the target address.
 *
 * @param target     The target address. Has to be a fully qualified address. The request is send as-is to this address.
 * @param hsRequest  The request data which should be send to the
 * @param hsResponse The response data which will contain the data returned by the proxied request to target.
 * @throws java.io.IOException Passed on from the connection logic.
 *//*from w w w  . ja v a2  s  .co  m*/
public static void execute(final String target, final String collection, final HttpServletRequest hsRequest,
        final HttpServletResponse hsResponse, MultiThreadedHttpConnectionManager connManager)
        throws IOException {
    // log.info("execute, target is " + target);
    // log.info("response commit state: " + hsResponse.isCommitted());

    if (target == null || "".equals(target) || "".equals(target.trim())) {
        log.error("The target address is not given. Please provide a target address.");
        return;
    }

    // log.info("checking url");
    final URL url;
    try {
        url = new URL(target);
    } catch (MalformedURLException e) {
        // log.error("The provided target url is not valid.", e);
        return;
    }

    // log.info("setting up the host configuration");

    final HostConfiguration config = new HostConfiguration();

    ProxyHost proxyHost = getUseProxyServer((String) hsRequest.getAttribute("use-proxy"));
    if (proxyHost != null)
        config.setProxyHost(proxyHost);

    final int port = url.getPort() != -1 ? url.getPort() : url.getDefaultPort();
    config.setHost(url.getHost(), port, "http");

    // log.info("config is " + config.toString());

    final HttpMethod targetRequest = setupProxyRequest(hsRequest, url);
    if (targetRequest == null) {
        // log.error("Unsupported request method found: " + hsRequest.getMethod());
        return;
    }

    //perform the request to the target server
    final HttpClient client = new HttpClient(connManager);
    //if (log.isInfoEnabled()) {
    // log.info("client state" + client.getState());
    // log.info("client params" + client.getParams().toString());
    // log.info("executeMethod / fetching data ...");
    //}

    final int result = client.executeMethod(config, targetRequest);

    //copy the target response headers to our response
    setupResponseHeaders(targetRequest, hsResponse);

    String binRegex = ".*\\.(?i)(jpg|tif|png|gif|bmp|mp3|mpg)(.*$)*";
    String binRegexRedux = ".*(?i)(\\/thumb)(.*$)*";

    if (target.matches(binRegex) || target.matches(binRegexRedux)) {
        // log.info("binRegex matched: " + target);
        InputStream originalResponseStream = targetRequest.getResponseBodyAsStream();

        if (originalResponseStream != null) {

            if (targetRequest.getResponseHeaders().toString().matches("(?i).*content-type.*")) {
                PrintWriter responseStream = hsResponse.getWriter();
                copyStreamText(targetRequest.getResponseBodyAsString(), responseStream);
            } else {
                OutputStream responseStream = hsResponse.getOutputStream();
                copyStreamBinary(originalResponseStream, responseStream);
            }
        }

    } else {
        // log.info("binRegex NOT matched: " + target);
        String proxyResponseStr = targetRequest.getResponseBodyAsString();
        // the body might be null, i.e. for responses with cache-headers which leave out the body

        if (proxyResponseStr != null) {
            //proxyResponseStr = proxyResponseStr.replaceAll("xqy", "jsp");

            proxyResponseStr = proxyResponseStr.replaceAll("National Library Catalog",
                    "Library of Congress Data Service");
            proxyResponseStr = proxyResponseStr.replaceAll("Library of Congress collections",
                    "Library of Congress bibliographic data");
            proxyResponseStr = proxyResponseStr.replaceAll("Library of Congress Collections",
                    "Library of Congress Bibliographic Data");

            proxyResponseStr = proxyResponseStr.replaceAll("action=\"/", "action=\"/diglib/");
            proxyResponseStr = proxyResponseStr.replaceAll("href=\"/", "href=\"/diglib/");
            proxyResponseStr = proxyResponseStr.replaceAll("href=\"/diglib/loc\\.",
                    "href=\"/diglib/" + collection + "/loc.");
            proxyResponseStr = proxyResponseStr.replaceAll("src=\"/", "src=\"/diglib/");
            proxyResponseStr = proxyResponseStr.replaceAll("value=\"/", "value=\"/diglib/");
            proxyResponseStr = proxyResponseStr.replaceAll("url\\(/", "url\\(/diglib/");
            proxyResponseStr = proxyResponseStr.replaceAll("url\\(\"/", "url\\(\"/diglib/");
            proxyResponseStr = proxyResponseStr.replaceAll("src'\\) == \"/", "src'\\) == \"/diglib/");
            proxyResponseStr = proxyResponseStr.replaceAll("src\", \"/", "src\", \"/diglib/");
            proxyResponseStr = proxyResponseStr.replaceAll("natlibcat@loc.gov", "ndmso@loc.gov");

            proxyResponseStr = proxyResponseStr.replaceAll("/nlc/", "/lcds/");
            proxyResponseStr = proxyResponseStr.replaceAll("/lcwa/", "/lcwanew/");
            //proxyResponseStr = proxyResponseStr.replaceAll("/tohap/", "/x-tohap/");

            proxyResponseStr = proxyResponseStr.replaceAll(".xqy", ".jsp");

            PrintWriter responseStream = hsResponse.getWriter();
            copyStreamText(proxyResponseStr, responseStream);
        }
    }

    // log.info("set up response, result code was " + result);
    targetRequest.releaseConnection();

    // SimpleHttpConnectionManager connManager = (SimpleHttpConnectionManager) client.getHttpConnectionManager();
    // connManager.closeIdleConnections(1000);

    // HttpConnection httpConn = connManager.getConnection(config);
    // httpConn.releaseConnection();

}

From source file:edu.utah.further.core.ws.HttpResponseTo.java

/**
 * Copy-constructor from an {@link HttpMethod}.
 * /*from w  w  w.  j a  v a 2  s . c om*/
 * @param method
 *            method to copy fields from
 */
public HttpResponseTo(final HttpMethod method) throws IOException {
    this.httpMethod = edu.utah.further.core.api.ws.HttpMethod.valueOf(method.getName());
    this.statusLine = method.getStatusLine();

    for (final Header header : method.getResponseHeaders()) {
        this.responseHeaders.addHeader(new Header(header.getName(), header.getValue()));
    }

    this.path = method.getPath();
    this.queryString = method.getQueryString();
    this.responseBody = method.getResponseBody();
    setParams(method.getParams());
}

From source file:com.zimbra.qa.unittest.TestWsdlServlet.java

String doWsdlServletRequest(String wsdlUrl, boolean admin, int expectedCode) throws Exception {
    Server localServer = Provisioning.getInstance().getLocalServer();

    String protoHostPort;// w  w w. j av  a  2 s  . c o  m
    if (admin)
        protoHostPort = "https://localhost:" + localServer.getIntAttr(Provisioning.A_zimbraAdminPort, 0);
    else
        protoHostPort = "http://localhost:" + localServer.getIntAttr(Provisioning.A_zimbraMailPort, 0);

    String url = protoHostPort + wsdlUrl;

    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);

    try {
        int respCode = HttpClientUtil.executeMethod(client, method);
        int statusCode = method.getStatusCode();
        String statusLine = method.getStatusLine().toString();

        ZimbraLog.test.debug("respCode=" + respCode);
        ZimbraLog.test.debug("statusCode=" + statusCode);
        ZimbraLog.test.debug("statusLine=" + statusLine);

        assertTrue("Response code", respCode == expectedCode);
        assertTrue("Status code", statusCode == expectedCode);

        Header[] respHeaders = method.getResponseHeaders();
        for (int i = 0; i < respHeaders.length; i++) {
            String header = respHeaders[i].toString();
            ZimbraLog.test.debug("ResponseHeader:" + header);
        }

        String respBody = method.getResponseBodyAsString();
        // ZimbraLog.test.debug("Response Body:" + respBody);
        return respBody;

    } catch (HttpException e) {
        fail("Unexpected HttpException" + e);
        throw e;
    } catch (IOException e) {
        fail("Unexpected IOException" + e);
        throw e;
    } finally {
        method.releaseConnection();
    }
}

From source file:com.springsource.insight.plugin.apache.http.hc3.HttpClientExecutionCollectionAspectTest.java

private void assertHeadersContents(String uri, String type, OperationMap details, HttpMethod method,
        boolean useRequestHeaders) {
    OperationList headers = details.get("headers", OperationList.class);
    assertNotNull("No " + type + " headers for " + uri, headers);

    Header[] hdrArray = useRequestHeaders ? method.getRequestHeaders() : method.getResponseHeaders();
    int numHdrs = (hdrArray == null) ? 0 : hdrArray.length;
    assertEquals("Mismatched " + type + " number of headers", numHdrs, headers.size());
    if (numHdrs <= 0) {
        return;// w  w  w .ja  va 2s  .co  m
    }

    Map<String, String> opHdrs = toHeadersMap(headers);
    Map<String, String> msgHdrs = toHeadersMap(hdrArray);
    assertEquals("Mismatched " + type + " headers map size", msgHdrs.size(), opHdrs.size());

    for (Map.Entry<String, String> hdrValue : msgHdrs.entrySet()) {
        String name = hdrValue.getKey();
        assertEquals("Mismatched " + type + " value for " + name + " header", hdrValue.getValue(),
                opHdrs.get(name));
    }
}