name.chengchao.myhttpclient.version3_1.HttpClient3UtilError.java Source code

Java tutorial

Introduction

Here is the source code for name.chengchao.myhttpclient.version3_1.HttpClient3UtilError.java

Source

/**
 * Project: armory-core
 * 
 * File Created at 2010-6-18
 * $Id$
 * 
 * Copyright 2008 Alibaba.com Croporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * Alibaba Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Alibaba.com.
 */
package name.chengchao.myhttpclient.version3_1;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

/**
 * @author charles.chengc
 */
public class HttpClient3UtilError {

    private static Logger logger = Logger.getLogger(HttpClient3UtilError.class);

    private final static String DEFAULT_CHARSETNAME = "UTF-8";
    private final static int DEFAULT_TIMEOUT = 15000;

    public static void main(String[] args) throws Exception {
        for (int i = 0; i < 10; i++) {
            String result = getDataAsStringFromUrl("http://www.chengchao.name/css/style.css");
            System.out.println(result);
            Thread.sleep(2000);
        }
        Thread.sleep(1000000);
    }

    /**
     * ?url?ResponseBody,method=get
     * 
     * @param url exp:http://192.168.1.1:8080/dir/target.html
     * @return byte[]?
     */
    public static byte[] getDataFromUrl(String url, int timeout) {
        if (StringUtils.isBlank(url)) {
            logger.error("url is blank!");
            return null;
        }
        HttpClient httpClient = new HttpClient();
        // 
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(8000);
        // ?
        httpClient.getParams().setSoTimeout(timeout);
        GetMethod method = new GetMethod(url);

        // fix???
        // method.setRequestHeader("Connection", "close");
        // ??1
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(1, false));
        try {
            int statusCode = httpClient.executeMethod(method);
            if (statusCode == HttpStatus.SC_OK) {
                return method.getResponseBody();
            } else {
                throw new RuntimeException("http request error,return code:" + statusCode + ",msg:"
                        + new String(method.getResponseBody()));
            }
        } catch (HttpException e) {
            method.abort();
            logger.error(e.getMessage());
        } catch (IOException e) {
            method.abort();
            logger.error(e.getMessage());
        } finally {
            // Release the connection.
            method.releaseConnection();
        }
        return null;
    }

    /**
     * ?url?ResponseBody,method=get
     * 
     * @param url exp:http://192.168.1.1:8080/dir/target.html
     * @param charsetName exp:http://192.168.1.1:8080/dir/target.html
     * @param timeout
     * @return String?
     * @throws UnsupportedEncodingException
     */
    public static String getDataAsStringFromUrl(String url, String charsetName, int timeout) {
        if (StringUtils.isBlank(url)) {
            logger.error("url is blank!");
            return null;
        }
        if (StringUtils.isBlank(charsetName)) {
            charsetName = DEFAULT_CHARSETNAME;
        }
        byte[] responseBody = getDataFromUrl(url, timeout);
        if (null != responseBody) {
            try {
                return new String(responseBody, charsetName);
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e.getMessage());
            }
        }
        return null;
    }

    public static String getDataAsStringFromUrl(String url) {
        return getDataAsStringFromUrl(url, null, DEFAULT_TIMEOUT);
    }

}