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

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

Introduction

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

Prototype

public abstract Header[] getRequestHeaders();

Source Link

Usage

From source file:TrivialApp.java

public static void main(String[] args) {
    if ((args.length != 1) && (args.length != 3)) {
        printUsage();/*from  www  .  ja va 2s.c  om*/
        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  av  a 2s  . 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.itude.mobile.mobbl.server.util.HeaderUtil.java

public static void printRequestHeaders(Logger logger, HttpMethod method) {
    if (method == null)
        throw new IllegalArgumentException("Method can't be null");
    if (logger == null)
        throw new IllegalArgumentException("Logger can't be null");

    logger.debug("List of request parameters:");

    Header[] headers = method.getRequestHeaders();
    if (headers != null) {
        for (Header h : headers)
            logger.debug(h.getName() + ":" + h.getValue());
    }/* w  w  w.  java2  s .com*/
}

From source file:com.groupon.odo.HttpUtilities.java

/**
 * Obtain newline-delimited headers from method
 *
 * @param method// w ww  .  j ava  2  s  . c  o  m
 * @return
 */
public static String getHeaders(HttpMethod method) {
    String headerString = "";
    Header[] headers = method.getRequestHeaders();
    for (Header header : headers) {
        if (headerString.length() != 0)
            headerString += "\n";

        headerString += header.getName() + ": " + header.getValue();
    }

    return headerString;
}

From source file:lucee.commons.net.http.httpclient3.HttpMethodCloner.java

/**
* Clones a HttpMethod. &ltbr>/*from  w  ww.j  a  va  2  s. c  om*/
* &ltb&gtAttention:</b> You have to clone a method before it has
* been executed, because the URI can change if followRedirects
* is set to true.
*
* @param m the HttpMethod to clone
*
* @return the cloned HttpMethod, null if the HttpMethod could
* not be instantiated
*
* @throws java.io.IOException if the request body couldn't be read
*/
public static HttpMethod clone(HttpMethod m) {
    HttpMethod copy = null;
    try {
        copy = m.getClass().newInstance();
    } catch (InstantiationException iEx) {
    } catch (IllegalAccessException iaEx) {
    }
    if (copy == null) {
        return null;
    }
    copy.setDoAuthentication(m.getDoAuthentication());
    copy.setFollowRedirects(m.getFollowRedirects());
    copy.setPath(m.getPath());
    copy.setQueryString(m.getQueryString());

    Header[] h = m.getRequestHeaders();
    int size = (h == null) ? 0 : h.length;

    for (int i = 0; i < size; i++) {
        copy.setRequestHeader(new Header(h[i].getName(), h[i].getValue()));
    }
    copy.setStrictMode(m.isStrictMode());
    if (m instanceof HttpMethodBase) {
        copyHttpMethodBase((HttpMethodBase) m, (HttpMethodBase) copy);
    }
    if (m instanceof EntityEnclosingMethod) {
        copyEntityEnclosingMethod((EntityEnclosingMethod) m, (EntityEnclosingMethod) copy);
    }
    return copy;
}

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

/**
 * ?log.//from  ww  w  .  ja  va 2s.  c  o m
 * 
 * @param httpMethod
 *            the http method
 * @return the http method attribute map for log
 */
private static Map<String, Object> getHttpMethodRequestAttributeMapForLog(HttpMethod httpMethod) {
    Map<String, Object> map = new LinkedHashMap<String, Object>();
    try {
        map.put("httpMethod.getName()", httpMethod.getName());
        map.put("httpMethod.getURI()", httpMethod.getURI().toString());
        map.put("httpMethod.getPath()", httpMethod.getPath());
        map.put("httpMethod.getQueryString()", httpMethod.getQueryString());

        map.put("httpMethod.getRequestHeaders()", httpMethod.getRequestHeaders());

        map.put("httpMethod.getDoAuthentication()", httpMethod.getDoAuthentication());
        map.put("httpMethod.getFollowRedirects()", httpMethod.getFollowRedirects());
        map.put("httpMethod.getHostAuthState()", httpMethod.getHostAuthState().toString());

        // HttpMethodParams httpMethodParams = httpMethod.getParams();
        // map.put("httpMethod.getParams()", httpMethodParams);
        map.put("httpMethod.getProxyAuthState()", httpMethod.getProxyAuthState().toString());

    } catch (Exception e) {
        log.error(e.getClass().getName(), e);
    }
    return map;
}

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

/**
 * ?log./*from  w  w w .jav  a 2  s . c om*/
 *
 * @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.mosso.client.cloudfiles.FilesResponse.java

/**
 * @param method The HttpMethod that generated this response
 *//*from   w  w w  . ja  v  a2s .  co  m*/
public FilesResponse(HttpMethod method) {
    httpmethod = method;

    if (logger.isDebugEnabled()) {
        logger.debug("Request Method: " + method.getName());
        logger.debug("Request Path: " + method.getPath());
        logger.debug("Status Line: " + getStatusLine());
        Header[] reqHeaders = method.getRequestHeaders();
        for (Header rH : reqHeaders)
            logger.debug(rH.toExternalForm());

        Header[] responseHeaders = getResponseHeaders();
        for (int i = 0; i < responseHeaders.length; i++)
            logger.debug(responseHeaders[i]);
    }
}

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

private void logRequestInfo(HttpMethod method, String body) throws IOException {
    if (!mDebugEnabled) {
        return;//from   w  w w .  java 2 s . com
    }
    StringBuilder reqLog = new StringBuilder();
    reqLog.append("WebDAV request:\n").append(method.getName()).append(" ").append(method.getURI().toString());
    reqLog.append('\n');
    Header headers[] = method.getRequestHeaders();
    if (headers != null && headers.length > 0) {
        for (Header hdr : headers) {
            String hdrName = hdr.getName();
            reqLog.append(hdrName).append('=');
            if (hdrName.contains("Auth") || (hdrName.contains(HttpHeaders.COOKIE))) {
                reqLog.append("*** REPLACED ***\n");
            } else {
                reqLog.append(hdr.getValue()).append('\n');
            }
        }
    }
    if (Strings.isNullOrEmpty(body) || !ZimbraLog.dav.isTraceEnabled()) {
        ZimbraLog.dav.debug(reqLog.toString());
    } else {
        ZimbraLog.dav.debug("%s\n%s", reqLog.toString(), body);
    }
}

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 ww .  j a  v  a  2  s . c om
    }

    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));
    }
}