Example usage for org.apache.commons.httpclient Header toString

List of usage examples for org.apache.commons.httpclient Header toString

Introduction

In this page you can find the example usage for org.apache.commons.httpclient Header toString.

Prototype

public String toString() 

Source Link

Usage

From source file:org.moxie.proxy.connection.ProxyRequestHandler.java

private void serveHeadURL(String downloadURL) throws IOException {
    URL url = new URL(downloadURL);
    url = config.getRedirect(url);/* ww w  .ja va  2s  .c  o m*/

    if (!"http".equals(url.getProtocol()))
        throw new IOException("Can only handle HTTP requests, got " + downloadURL);

    ProxyHead d = new ProxyHead(config, url);
    try {
        d.download();
    } catch (DownloadFailed e) {
        log.severe(e.getMessage());
    }
    println(d.getStatusLine());
    for (Header h : d.getResponseHeaders()) {
        print(h.toString());
    }
    println();
    InputStream data = new BufferedInputStream(new ByteArrayInputStream(d.getResponseBody()));
    copy(data, out);
    data.close();
}

From source file:org.mozilla.zest.impl.ZestBasicRunner.java

private String arrayToStr(Header[] headers) {
    StringBuilder sb = new StringBuilder();
    for (Header header : headers) {
        sb.append(header.toString());
    }/*from  w w  w . j av  a2  s .co  m*/
    return sb.toString();
}

From source file:org.mulgara.resolver.http.HttpContent.java

/**
 * Obtain a valid connection and follow redirects if necessary.
 * //from w  w w.j  a  v  a 2  s.c o m
 * @param methodType request the headders (HEAD) or body (GET)
 * @return valid connection method. Can be null.
 * @throws NotModifiedException  if the content validates against the cache
 * @throws IOException  if there's difficulty communicating with the web site
 */
private HttpMethod establishConnection(int methodType) throws IOException, NotModifiedException {
    if (logger.isDebugEnabled())
        logger.debug("Establishing connection");

    HttpMethod method = getConnectionMethod(methodType);
    assert method != null;
    Header header = null;

    /*
      // Add cache validation headers to the request
      if (lastModifiedMap.containsKey(httpUri)) {
        String lastModified = (String) lastModifiedMap.get(httpUri);
        assert lastModified != null;
        method.addRequestHeader("If-Modified-Since", lastModified);
      }
            
      if (eTagMap.containsKey(httpUri)) {
        String eTag = (String) eTagMap.get(httpUri);
        assert eTag != null;
        method.addRequestHeader("If-None-Match", eTag);
      }
     */

    // Make the request
    if (logger.isDebugEnabled())
        logger.debug("Executing HTTP request");
    connection.open();
    method.execute(state, connection);
    if (logger.isDebugEnabled()) {
        logger.debug("Executed HTTP request, response code " + method.getStatusCode());
    }

    // Interpret the response header
    if (method.getStatusCode() == HttpStatus.SC_NOT_MODIFIED) {
        // cache has been validated
        throw new NotModifiedException(httpUri);
    } else if (!isValidStatusCode(method.getStatusCode())) {
        throw new UnknownHostException("Unable to obtain connection to " + httpUri + ". Returned status code "
                + method.getStatusCode());
    } else {
        // has a redirection been issued
        int numberOfRedirection = 0;
        while (isRedirected(method.getStatusCode()) && numberOfRedirection <= MAX_NO_REDIRECTS) {

            // release the existing connection
            method.releaseConnection();

            //attempt to follow the redirects
            numberOfRedirection++;

            // obtain the new location
            header = method.getResponseHeader("location");
            if (header != null) {
                try {
                    initialiseSettings(new URL(header.getValue()));
                    if (logger.isInfoEnabled()) {
                        logger.info("Redirecting to " + header.getValue());
                    }

                    // attempt a new connection to this location
                    method = getConnectionMethod(methodType);
                    connection.open();
                    method.execute(state, connection);
                    if (!isValidStatusCode(method.getStatusCode())) {
                        throw new UnknownHostException(
                                "Unable to obtain connection to " + " the redirected site " + httpUri
                                        + ". Returned status code " + method.getStatusCode());
                    }
                } catch (URISyntaxException ex) {
                    throw new IOException(
                            "Unable to follow redirection to " + header.getValue() + " Not a valid URI");
                }
            } else {
                throw new IOException("Unable to obtain redirecting detaild from " + httpUri);
            }
        }
    }

    // Update metadata about the cached document
    Header lastModifiedHeader = method.getResponseHeader("Last-Modified");
    if (lastModifiedHeader != null) {
        logger.debug(lastModifiedHeader.toString());
        assert lastModifiedHeader.getElements().length >= 1;
        assert lastModifiedHeader.getElements()[0].getName() != null;
        assert lastModifiedHeader.getElements()[0].getName() instanceof String;
        // previous code: added to cache
    }

    Header eTagHeader = method.getResponseHeader("Etag");
    if (eTagHeader != null) {
        logger.debug(eTagHeader.toString());
        assert eTagHeader.getElements().length >= 1;
        assert eTagHeader.getElements()[0].getName() != null;
        assert eTagHeader.getElements()[0].getName() instanceof String;
        // previous code: added to cache
    }

    return method;
}

From source file:org.osaf.caldav4j.methods.CalendarCalDAVReportMethod.java

/**
 * Return the length (in bytes) of my request body, suitable for use in a
 * <tt>Content-Length</tt> header.
 *
 * <p>/*from  w  w w .  ja va  2s . co m*/
 * Return <tt>-1</tt> when the content-length is unknown.
 * </p>
 *
 * <p>
 * This implementation returns <tt>0</tt>, indicating that the request has
 * no body.
 * </p>
 *
 * @return <tt>0</tt>, indicating that the request has no body.
 */
@Override
protected int getRequestContentLength() {
    if (!isRequestContentAlreadySet()) {
        String contents = generateRequestBody();
        // be nice - allow overriding functions to return null or empty
        // strings for no content.
        if (contents == null)
            contents = "";

        setRequestBody(contents);

        if (debug > 0) {
            System.out.println("\n>>>>>>>  to  server  ---------------------------------------------------");
            System.out.println(getName() + " " + getPath()
                    + (getQueryString() != null ? "?" + getQueryString() : "") + " " + "HTTP/1.1");

            Header[] headers = getRequestHeaders();
            for (int i = 0; i < headers.length; i++) {
                Header header = headers[i];
                System.out.print(header.toString());
            }
            System.out.println("Content-Length: " + super.getRequestContentLength());

            if (this instanceof DepthSupport) {
                System.out.println("Depth: " + ((DepthSupport) this).getDepth());
            }

            System.out.println();
            xo.print(contents);
            System.out.println("------------------------------------------------------------------------");
        }

    }

    return super.getRequestContentLength();
}

From source file:org.wso2.carbon.mashup.javascript.hostobjects.pooledhttpclient.HttpCommand.java

private SimpleHttpResponse toResponse(HttpMethod method) {
    SimpleHttpResponse response;/*from www .j a  v a2s  .  c om*/
    Header[] headers = method.getResponseHeaders();
    String headersString = "";
    for (Header header : headers) {
        headersString += header.toString();
    }
    try {
        response = new SimpleHttpResponse(method.getStatusCode(), method.getStatusText(), headersString,
                method.getResponseBodyAsString());
    } catch (Exception e) {
        throw new RuntimeException("", e);
    }
    return response;
}

From source file:smile.weixin.jdquanyi.tools.SendMsg_webchinese.java

/** 
 * @author dengsilinming /* w  w  w  .  ja v a2 s  .  co  m*/
 * @date Sep 18, 2012 
 * @time 9:38:25 AM 
 * @param args 
 * @throws IOException 
 * @throws HttpException 
 * @description 
 */
public void send(String telephone, int id) throws HttpException, IOException {
    HttpClient client = new HttpClient();
    PostMethod post = new PostMethod("http://gbk.sms.webchinese.cn");
    // PostMethod post = new PostMethod("http://sms.webchinese.cn/web_api/");  
    post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=gbk");//   
    NameValuePair[] data = { new NameValuePair("Uid", "jdquanyi"), //   
            new NameValuePair("Key", "82594d54b061255b1d6d"), //   
            new NameValuePair("smsMob", telephone), //   
            new NameValuePair("smsText", "yzm " + id) };//   
    post.setRequestBody(data);

    client.executeMethod(post);
    Header[] headers = post.getResponseHeaders();
    int statusCode = post.getStatusCode();
    System.out.println("statusCode:" + statusCode);
    for (Header h : headers) {
        System.out.println("---" + h.toString());
    }
    String result = new String(post.getResponseBodyAsString().getBytes("gbk"));
    System.out.println(result);
    post.releaseConnection();

}