HttpClient学习

1、好的文章:

http://blog.youkuaiyun.com/wangpeng047/article/details/19624529

http://www.cnblogs.com/loveyakamoz/archive/2011/07/21/2113252.html

http://www.cnblogs.com/loveyakamoz/archive/2011/07/21/2112804.html


2.使用commons-httpclient封装的:需要导入commons-client.jar  commons-logging.jar   commons-codec.jar

(1)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
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.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;

public class HttpUtil {


    private static MultiThreadedHttpConnectionManager manager              = new MultiThreadedHttpConnectionManager();
    private static int                                maxConnectionPerHost = 15;
    private static int                                maxTotalConnections  = 40;

    private static final int                          CONN_OUT_TIME             = 10 * 1000;
    private static final int                          SO_OUT_TIME             = 240 * 1000;
    // 初始化ConnectionManger的方法
    public static void setPara(int timeout) {
        manager.getParams().setConnectionTimeout(timeout);
        manager.getParams().setSoTimeout(timeout);
        manager.getParams().setDefaultMaxConnectionsPerHost(maxConnectionPerHost);
        manager.getParams().setMaxTotalConnections(maxTotalConnections);
    }

    /**
     * get请求,默认超时5s
     * 
     * @param restUrl
     * @param timeoutMillions
     * @return
     */
    public static String getResponseByHttp(String restUrl) {
        String responseStr = null;
        HttpClient client = new HttpClient();
        HttpMethod method = new GetMethod(restUrl);
        client.getHttpConnectionManager().getParams().setConnectionTimeout(CONN_OUT_TIME);
        client.getHttpConnectionManager().getParams().setSoTimeout(SO_OUT_TIME);
        method.setRequestHeader("rest-who", "aries");
        method.setRequestHeader("rest-code", "ccc558986e26577ce68b579995bfa01a");
        try {
            client.executeMethod(method);
            method.getParams().setContentCharset("UTF-8");
            if (method.getStatusCode() == HttpStatus.SC_OK) {
                responseStr = method.getResponseBodyAsString();
            }
        } catch (Exception e) {
//            log.error("request out of time, CONN_OUT_TIME="+CONN_OUT_TIME+", SO_OUT_TIME="+SO_OUT_TIME+", URL="+restUrl,e);
        }

        method.releaseConnection();

        return responseStr;
    }

    /**
     * get请求
     * 
     * @param url
     * @param encode
     * @param timeOut
     * @return
     */
    public static ResultDto<Integer, String> getGetResponseByHttp(String url, String encode, int timeout)
                                                                                                        throws HttpException,
                                                                                                        IOException {
        HttpUtil.setPara(timeout);
        HttpClient client = new HttpClient(manager);
        GetMethod get = new GetMethod(url);
        get.setFollowRedirects(true);
        get.setRequestHeader("refer", "aries");
        // 设置重试次数
        get.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(1, false));
        int responseCode = HttpStatus.SC_NOT_FOUND;
        StringBuffer resultBuffer = new StringBuffer();
        String resultStr = null;
        try {
            responseCode = client.executeMethod(get);
            BufferedReader in = new BufferedReader(new InputStreamReader(get.getResponseBodyAsStream(),
                                                                         get.getResponseCharSet()));
            String inputLine = null;
            while ((inputLine = in.readLine()) != null) {
                resultBuffer.append(inputLine);
            }
            in.close();
            resultStr = HttpUtil.ConverterStringCode(resultBuffer.toString(), get.getResponseCharSet(), encode);
        } finally {
            get.releaseConnection();
        }
        if (responseCode > HttpStatus.SC_OK) {
//            logger.error("url: " + url + " get error! return code is: " + responseCode);
        }
        return new ResultDto<Integer, String>(responseCode, resultStr);
    }

    public static ResultDto<Integer, String> getPostResponseWithHttpClient(String url, String encode,
                                                                          String requestData, int timeout,String type)
                                                                                                                   throws HttpException,
                                                                                                                   IOException {
        HttpClient client = new HttpClient(manager);
        HttpUtil.setPara(timeout);
        // 设置参数
        PostMethod mtd = new PostMethod(url);
        if(type.contains("XML")){
            mtd.setRequestEntity(new StringRequestEntity(requestData,"text/xml","utf-8"));  
        }else if (type.contains("JSON")){
            mtd.setRequestEntity(new StringRequestEntity(requestData,"text/json","utf-8"));
        }else{
            mtd.setRequestEntity(new StringRequestEntity(requestData,null,"utf-8"));
        }
        int responseCode = HttpStatus.SC_NOT_FOUND;
        String resultStr = null;
        try {
            responseCode = client.executeMethod(mtd);
            BufferedReader in = new BufferedReader(new InputStreamReader(mtd.getResponseBodyAsStream(),
                                                                         mtd.getResponseCharSet()));

            String inputLine = null;
            StringBuffer resultBuffer = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                resultBuffer.append(inputLine);
            }
            in.close();
            resultStr = resultBuffer.toString();
            resultStr = HttpUtil.ConverterStringCode(resultBuffer.toString(), mtd.getResponseCharSet(), encode);
        } finally {
            mtd.releaseConnection();
        }
        if (responseCode > HttpStatus.SC_OK) {
//            logger.error("url: " + url + " get error! return code is: " + responseCode);
        }

        return new ResultDto<Integer, String>(responseCode, resultStr);

    }

    private static String ConverterStringCode(String source, String srcEncode, String destEncode) {
        if (source != null) {
            try {
                return new String(source.getBytes(srcEncode), destEncode);
            } catch (UnsupportedEncodingException e) {
                return "";
            }
        } else {
            return "";
        }
    }
}
(2)dto类

public class ResultDto<A,B> {
	private A first;
	private B second;
	
	public ResultDto(A first,B second) {
		this.first = first;
		this.second = second;
	}
	public A getFirst() {
		return first;
	}
	public void setFirst(A first) {
		this.first = first;
	}
	public B getSecond() {
		return second;
	}
	public void setSecond(B second) {
		this.second = second;
	}
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值