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:TrivialApp.java

public static void main(String[] args) {
    if ((args.length != 1) && (args.length != 3)) {
        printUsage();//www  . j  a  v  a 2s .c  o m
        System.exit(-1);
    }

    Credentials creds = null;
    if (args.length >= 3) {
        creds = new UsernamePasswordCredentials(args[1], args[2]);
    }

    //create a singular HttpClient object
    HttpClient client = new HttpClient();

    //establish a connection within 5 seconds
    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

    //set the default credentials
    if (creds != null) {
        client.getState().setCredentials(AuthScope.ANY, creds);
    }

    String url = args[0];
    HttpMethod method = null;

    //create a method object
    method = new GetMethod(url);
    method.setFollowRedirects(true);
    //} catch (MalformedURLException murle) {
    //    System.out.println("<url> argument '" + url
    //            + "' is not a valid URL");
    //    System.exit(-2);
    //}

    //execute the method
    String responseBody = null;
    try {
        client.executeMethod(method);
        responseBody = method.getResponseBodyAsString();
    } catch (HttpException he) {
        System.err.println("Http error connecting to '" + url + "'");
        System.err.println(he.getMessage());
        System.exit(-4);
    } catch (IOException ioe) {
        System.err.println("Unable to connect to '" + url + "'");
        System.exit(-3);
    }

    //write out the request headers
    System.out.println("*** Request ***");
    System.out.println("Request Path: " + method.getPath());
    System.out.println("Request Query: " + method.getQueryString());
    Header[] requestHeaders = method.getRequestHeaders();
    for (int i = 0; i < requestHeaders.length; i++) {
        System.out.print(requestHeaders[i]);
    }

    //write out the response headers
    System.out.println("*** Response ***");
    System.out.println("Status Line: " + method.getStatusLine());
    Header[] responseHeaders = method.getResponseHeaders();
    for (int i = 0; i < responseHeaders.length; i++) {
        System.out.print(responseHeaders[i]);
    }

    //write out the response body
    System.out.println("*** Response Body ***");
    System.out.println(responseBody);

    //clean up the connection resources
    method.releaseConnection();

    System.exit(0);
}

From source file:ExampleP2PHttpClient.java

public static void main(String[] args) {
    // initialize JXTA
    try {/*from   w  w w  .  j  a  va 2  s. c  o m*/
        // sign in and initialize the JXTA network; profile this peer and create it
        // if it doesn't exist
        P2PNetwork.signin("clientpeer", "clientpeerpassword", "TestNetwork", true);
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }

    // register the P2P socket protocol factory
    Protocol jxtaHttp = new Protocol("p2phttp", new P2PProtocolSocketFactory(), 80);
    Protocol.registerProtocol("p2phttp", jxtaHttp);

    //create a singular HttpClient object
    HttpClient client = new HttpClient();

    //establish a connection within 50 seconds
    client.setConnectionTimeout(50000);

    String url = System.getProperty("url");
    if (url == null || url.equals("")) {
        System.out.println("You must provide a URL to access.  For example:");
        System.out.println("ant example-webclient-run -D--url=p2phttp://www.somedomain.foo");

        System.exit(1);
    }
    System.out.println("Connecting to " + url + "...");

    HttpMethod method = null;

    //create a method object
    method = new GetMethod(url);
    method.setFollowRedirects(true);
    method.setStrictMode(false);
    //} catch (MalformedURLException murle) {
    //    System.out.println("<url> argument '" + url
    //            + "' is not a valid URL");
    //    System.exit(-2);
    //}

    //execute the method
    String responseBody = null;
    try {
        client.executeMethod(method);
        responseBody = method.getResponseBodyAsString();
    } catch (HttpException he) {
        System.err.println("Http error connecting to '" + url + "'");
        System.err.println(he.getMessage());
        System.exit(-4);
    } catch (IOException ioe) {
        System.err.println("Unable to connect to '" + url + "'");
        System.exit(-3);
    }

    //write out the request headers
    System.out.println("*** Request ***");
    System.out.println("Request Path: " + method.getPath());
    System.out.println("Request Query: " + method.getQueryString());
    Header[] requestHeaders = method.getRequestHeaders();
    for (int i = 0; i < requestHeaders.length; i++) {
        System.out.print(requestHeaders[i]);
    }

    //write out the response headers
    System.out.println("*** Response ***");
    System.out.println("Status Line: " + method.getStatusLine());
    Header[] responseHeaders = method.getResponseHeaders();
    for (int i = 0; i < responseHeaders.length; i++) {
        System.out.print(responseHeaders[i]);
    }

    //write out the response body
    System.out.println("*** Response Body ***");
    System.out.println(responseBody);

    //clean up the connection resources
    method.releaseConnection();
    method.recycle();

    System.exit(0);
}

From source file:com.foglyn.fogbugz.Utils.java

/**
 * Converts response headers into map.// w  ww .  jav a2  s  .  c  o m
 * 
 * @param method
 * @return Map with header name/value pairs. All header names are in lowercase.
 */
static Map<String, String> convertHeadersToMap(HttpMethod method) {
    Map<String, String> result = new LinkedHashMap<String, String>();

    Header[] headers = method.getResponseHeaders();
    for (Header h : headers) {
        result.put(h.getName().toLowerCase(), h.getValue());
    }
    return result;
}

From source file:edu.du.penrose.systems.fedoraProxy.web.bus.ProxyController.java

/**
 * Call the HttpMethod and write all results and status to the HTTP response
 * object./* w  ww.  j a v a  2 s  .  c  o m*/
 * 
 * THIS IS THE REQUEST WE NEED TO DUPLICATE GET
 * /fedora/get/codu:72/ECTD_test_1_access.pdf HTTP/1.1 Host: localhost:8080
 * Connection: keep-alive Accept:
 * application/xml,application/xhtml+xml,text/
 * html;q=0.9,text/plain;q=0.8,image/png,*;q=0.5 User-Agent: Mozilla/5.0
 * (X11; U; Linux x86_64; en-US) AppleWebKit/534.10 (KHTML, like Gecko)
 * Chrome/8.0.552.215 Safari/534.10 Accept-Encoding: gzip,deflate,sdch
 * Accept-Language: en-US,en;q=0.8 Accept-Charset:
 * ISO-8859-1,utf-8;q=0.7,*;q=0.3 Cookie: fez_list=YjowOw%3D%3D
 * 
 * ACTUAL SENT GET /fedora/get/codu:72/ECTD_test_1_access.pdf HTTP/1.1
 * Accept:
 * application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q
 * =0.8,image/png,*;q=0.5 Connection: keep-alive Accept-Encoding:
 * gzip,deflate,sdch Accept-Language: en-US,en;q=0.8 Accept-Charset:
 * ISO-8859-1,utf-8;q=0.7,*;q=0.3 : User-Agent: Jakarta
 * Commons-HttpClient/3.1 Host: localhost:8080
 * 
 * @param proxyCommand
 * @param response
 * @param authenicate true to set Preemptive authentication
 */
public static void executeMethod(String proxyCommand, HttpServletResponse response, boolean authenicate) {
    HttpClient theClient = new HttpClient();

    HttpMethod method = new GetMethod(proxyCommand);

    setDefaultHeaders(method);

    setAdrCredentials(theClient, authenicate);

    try {
        theClient.executeMethod(method);
        response.setStatus(method.getStatusCode());

        // Set the content type, as it comes from the server
        Header[] headers = method.getResponseHeaders();
        for (Header header : headers) {

            if ("Content-Type".equalsIgnoreCase(header.getName())) {
                response.setContentType(header.getValue());
            }

            /**
             * Copy all headers, except Transfer-Encoding which is getting set
             * set elsewhere. At this point response.containsHeader(
             * "Transfer-Encoding" ) is false, however it is getting set twice
             * according to wireshark, therefore we do not set it here.
             */
            if (!header.getName().equalsIgnoreCase("Transfer-Encoding")) {
                response.setHeader(header.getName(), header.getValue());
            }
        }

        // Write the body, flush and close

        InputStream is = method.getResponseBodyAsStream();

        BufferedInputStream bis = new BufferedInputStream(is);

        StringBuffer sb = new StringBuffer();
        byte[] bytes = new byte[8192]; // reading as chunk of 8192 bytes
        int count = bis.read(bytes);
        while (count != -1 && count <= 8192) {
            response.getOutputStream().write(bytes, 0, count);
            count = bis.read(bytes);
        }

        bis.close();
        response.getOutputStream().flush();
        response.getOutputStream().close();
    } catch (Exception e) {
        logger.error(e.getMessage());
    } finally {
        method.releaseConnection();
    }
}

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

private static void setupResponseHeaders(HttpMethod httpMethod, HttpServletResponse hsResponse) {
    //if ( log.isInfoEnabled() ) {
    // log.info("setupResponseHeaders");
    // log.info("status text: " + httpMethod.getStatusText());
    // log.info("status line: " + httpMethod.getStatusLine());
    //}/*from  w  w w. j a  v a2s.  c om*/

    //String ctHeaderFullStr = "";
    String ctHeaderStr = "";
    boolean ctHeaderExists = false;
    for (int i = 0; i < httpMethod.getResponseHeaders().length; i++) {
        Header h = httpMethod.getResponseHeaders()[i];
        if ("content-type".equalsIgnoreCase(h.getName())) {
            //ctHeaderFullStr = h.toString();
            ctHeaderStr = h.getValue();
            //log.info("ctHeaderFullStr is " + ctHeaderFullStr);
            //log.info("ctHeaderStr is " + ctHeaderStr);
            if (ctHeaderStr.indexOf("audio/mpeg") > -1) {
                //log.info("We have a match.  ctHeaderExists is true");
                ctHeaderExists = true;
            }
        }
    }

    //filter the headers, which are copied from the proxy response. The http lib handles those itself.
    //Filtered out: the content encoding, the content length and cookies
    for (int i = 0; i < httpMethod.getResponseHeaders().length; i++) {
        Header h = httpMethod.getResponseHeaders()[i];
        if ("content-encoding".equalsIgnoreCase(h.getName())) {
            continue;
        } else if ("content-length".equalsIgnoreCase(h.getName()) && !ctHeaderExists) {
            continue;
        } else if ("transfer-encoding".equalsIgnoreCase(h.getName())) {
            continue;
        } else if (h.getName().toLowerCase().startsWith("cookie")) {
            //retrieving a cookie which sets the session id will change the calling session: bad! So we skip this header.
            continue;
        } else if (h.getName().toLowerCase().startsWith("set-cookie")) {
            //retrieving a cookie which sets the session id will change the calling session: bad! So we skip this header.
            continue;
        }

        hsResponse.addHeader(h.getName(), h.getValue());
        // log.info("setting response parameter:" + h.getName() + ", value: " + h.getValue());
    }
    // fix me what about the response footers? (httpMethod.getResponseFooters())

    if (httpMethod.getStatusCode() != 200) {
        hsResponse.setStatus(httpMethod.getStatusCode());
    }
}

From source file:de.bermuda.arquillian.example.ContentTypeProxyServlet.java

private void migrateResponseHeader(HttpServletResponse resp, HttpMethod post) {
    for (Header header : post.getResponseHeaders()) {
        if (!(header.getName().equalsIgnoreCase("Content-Type"))
                && !(header.getName().equalsIgnoreCase("Transfer-Encoding"))) {
            resp.addHeader(header.getName(), header.getValue());

            log.info("Copying response header: " + header.getName() + ": " + header.getValue());
        }/*from   ww  w .j  a  va2  s .c  o  m*/
    }
    resp.setContentType("application/soap+xml");
}

From source file:com.thoughtworks.go.agent.launcher.ServerCall.java

public static ServerResponseWrapper invoke(HttpMethod method) throws Exception {
    HashMap<String, String> headers = new HashMap<String, String>();
    HttpClient httpClient = new HttpClient();
    httpClient.setConnectionTimeout(HTTP_TIMEOUT_IN_MILLISECONDS);
    try {//from w w  w.ja  v a 2 s  . c  om
        final int status = httpClient.executeMethod(method);
        if (status == HttpStatus.SC_NOT_FOUND) {
            StringWriter sw = new StringWriter();
            PrintWriter out = new PrintWriter(sw);
            out.println("Return Code: " + status);
            out.println("Few Possible Causes: ");
            out.println("1. Your Go Server is down or not accessible.");
            out.println(
                    "2. This agent might be incompatible with your Go Server.Please fix the version mismatch between Go Server and Go Agent.");
            out.close();
            throw new Exception(sw.toString());
        }
        if (status != HttpStatus.SC_OK) {
            throw new Exception("Got status " + status + " " + method.getStatusText() + " from server");
        }
        for (Header header : method.getResponseHeaders()) {
            headers.put(header.getName(), header.getValue());
        }
        return new ServerResponseWrapper(headers, method.getResponseBodyAsStream());
    } catch (Exception e) {
        String message = "Couldn't access Go Server with base url: " + method.getURI() + ": " + e.toString();
        LOG.error(message);
        throw new Exception(message, e);
    } finally {
        method.releaseConnection();
    }
}

From source file:com.smartitengineering.util.rest.client.jersey.cache.CustomApacheHttpClientResponseResolver.java

private HTTPResponse convertResponse(HttpMethod method) {
    Headers headers = new Headers();
    for (Header header : method.getResponseHeaders()) {
        headers = headers.add(header.getName(), header.getValue());
    }/*from  ww  w. j  a va2s .  com*/
    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 = responseCreator.createResponse(line, headers, stream);
    } finally {
        if (stream == null) {
            method.releaseConnection();
        }
    }
    return response;
}

From source file:com.tasktop.c2c.server.web.proxy.HttpProxy.java

void copyProxyReponse(HttpMethod proxyResponse, HttpServletResponse response) throws IOException {
    copyProxyHeaders(proxyResponse.getResponseHeaders(), response);
    response.setContentLength(getResponseContentLength(proxyResponse));
    copy(proxyResponse.getResponseBodyAsStream(), response.getOutputStream());
    if (proxyResponse.getStatusLine() != null) {
        int statCode = proxyResponse.getStatusCode();
        response.setStatus(statCode);/*from ww  w .  ja v a 2s .c o  m*/
    }
}

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

public static void dumpResponse(int respCode, HttpMethod method, String prefix) throws IOException {

    prefix = prefix + " - ";

    // status//from w w w  . ja va  2s .  c  o m
    int statusCode = method.getStatusCode();
    String statusLine = method.getStatusLine().toString();

    System.out.println(prefix + "respCode=" + respCode);
    System.out.println(prefix + "statusCode=" + statusCode);
    System.out.println(prefix + "statusLine=" + statusLine);

    // headers
    System.out.println(prefix + "Headers");
    Header[] respHeaders = method.getResponseHeaders();
    for (int i = 0; i < respHeaders.length; i++) {
        String header = respHeaders[i].toString();
        // trim the CRLF at the end to save space
        System.out.println(prefix + header.trim());
    }

    // body
    byte[] bytes = ByteUtil.getContent(method.getResponseBodyAsStream(), 0);
    System.out.println(prefix + bytes.length + " bytes read");
    System.out.println(new String(bytes));
}