HTTP请求

环境:J2EE 5.0

HTTP请求工具类

package xxx.util;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.util.IdleConnectionTimeoutThread;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;


/**
 * httpClient处理
 */
public class HttpProtocolHandler {


    /** 连接超时时间,缺省为8秒钟 */
    private int  defaultConnectionTimeout = 8000;

    /** 回应超时时间,缺省为30秒钟 */
    private int  defaultSoTimeout = 30000;

    /** 闲置连接超时时间,缺省为60秒钟 */
    private int defaultIdleConnTimeout  = 60000;
    
    /**定义每台主机允许的最大连接数,默认为2*/
    private int defaultMaxConnPerHost = 80;
    
    /**httpConnectionManager管理的最大连接数,默认为20*/
    private int  defaultMaxTotalConn = 100;

    /** 默认等待HttpConnectionManager返回连接超时(只有在达到最大连接数时起作用)*/
    private static final long   defaultHttpConnectionManagerTimeout = 3 * 1000;

    /**  HTTP连接管理器,该连接管理器必须是线程安全的. */
    private HttpConnectionManager connectionManager;
    
    private static HttpProtocolHandler httpProtocolHandler  = new HttpProtocolHandler();   

    /**  工厂方法 */ 
    public static HttpProtocolHandler getInstance() {
        return httpProtocolHandler;
    }
    /**
     * 私有的构造方法
     */
    private HttpProtocolHandler() {
        // 创建一个线程安全的HTTP连接池
        connectionManager = new MultiThreadedHttpConnectionManager();
        connectionManager.getParams().setDefaultMaxConnectionsPerHost(defaultMaxConnPerHost);
        connectionManager.getParams().setMaxTotalConnections(defaultMaxTotalConn);
        connectionManager.getParams().setConnectionTimeout(defaultConnectionTimeout);
        connectionManager.getParams().setSoTimeout(defaultSoTimeout);
        
        connectionManager.getParams().setIntParameter("http.socket.timeout", 30000);  

        
        IdleConnectionTimeoutThread ict = new IdleConnectionTimeoutThread();
        ict.addConnectionManager(connectionManager);
        ict.setConnectionTimeout(defaultIdleConnTimeout);

        ict.start();
    }
    
    /**执行标志*/
    private static boolean execFlag = true;
    /**正在执行文件标志map*/
    private static Map<String, Integer> writingFlagMap = new HashMap<String, Integer>();
    /**恢复次数map*/
    private static Map<String, Integer> reConnectMap = new HashMap<String, Integer>();
    
	public  boolean isExecFlag() {
		return execFlag;
	}
	public  void setExecFlag(boolean execFlag) {
		HttpProtocolHandler.execFlag = execFlag;
	}
	public static Map<String, Integer> getWritingFlagMap() {
		return writingFlagMap;
	}
	public  void setWritingFlagMap(Map<String, Integer> writingFlagMap) {
		HttpProtocolHandler.writingFlagMap = writingFlagMap;
	}

	/* ******************* 以下是请求文件*********************** */
    /**
     * 请求文件
     * @param requestUrl
     * @param savePath
     * @return
     */
    public boolean executeGetFile(String requestUrl,String savePath){
    	HttpClient httpclient = new HttpClient(connectionManager);
        httpclient.getParams().setConnectionManagerTimeout(defaultHttpConnectionManagerTimeout);
        FileOutputStream out = null;
//        System.out.println("http://"+requestUrl);
 		HttpMethod method = new GetMethod("http://"+requestUrl);
 		InputStream in = null;
 		int len = -1;
 		byte[] b = new byte[1024];
 			try {
				httpclient.executeMethod(method);
				in = method.getResponseBodyAsStream();
				if(method.getStatusCode()!=200){
					System.out.println("信息:http://"+requestUrl+"访问失败,刷新信息失败。");
					return false;
				}
				out = new FileOutputStream(new File(savePath));
				while((len=in.read(b))!=-1){
					out.write(b, 0, len);
				}
				out.flush();
			} catch (HttpException e) {
				e.printStackTrace();return false;
			} catch (IOException e) {
				e.printStackTrace();return false;
			}finally{
				 try {
					if(out!=null){out.close();}
				} catch (IOException e) {
					e.printStackTrace();
				}
				 method.releaseConnection();
			}
			return true;
    }
    /**
     * 直接读取文件信息(对于文件不大的)
     * @param requestUrl
     * @return
     */
    public String executeGetString(String requestUrl){
    	HttpClient httpclient = new HttpClient(connectionManager);
        httpclient.getParams().setConnectionManagerTimeout(defaultHttpConnectionManagerTimeout);
 		HttpMethod method = new GetMethod("http://"+requestUrl);
// 		method.setRequestHeader("Cookie","JSESSIONID="+sessionID);
 		method.getParams().setContentCharset("UTF-8");
 		String resultStr = "";
 			try {
				httpclient.executeMethod(method);
				resultStr = method.getResponseBodyAsString();
				if(method.getStatusCode()!=200){
					return null;
				}
			} catch (HttpException e) {
				e.printStackTrace();
				return null;
			} catch (IOException e) {
				e.printStackTrace();
				return null;
			}finally{
				 method.releaseConnection();
			}
    	return resultStr;
    }
    /**
     * 直接读取文件信息(对于文件不大的)
     * @param requestUrl
     * @return
     */
    public String executeWSGetString(String requestUrl){
    	HttpClient httpclient = new HttpClient(connectionManager);
		httpclient.getParams().setConnectionManagerTimeout(defaultHttpConnectionManagerTimeout);
		HttpMethod method = new GetMethod("http://" + requestUrl);
		method.setRequestHeader("Sec-WebSocket-Key", "	esAjYnZeGHsnmqBc/BtOfA==");
		method.setRequestHeader("Upgrade", "websocket");
		method.getParams().setContentCharset("UTF-8");
		String resultStr = "";
		try {
			httpclient.executeMethod(method);
			resultStr = method.getResponseBodyAsString();
			if (method.getStatusCode() != 200) {
				return null;
			}
		} catch (HttpException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} finally {
			method.releaseConnection();
		}
		return resultStr;
    }

	/* ******************* 以下是POST带参数请求*********************** */
    /**
     * POST带参数请求
     * @param requestUrl
     * @param params
     * @return
     */
    public String executePostReq(String requestUrl,Map<String, String> params){
    	HttpClient httpclient = new HttpClient(connectionManager);
        httpclient.getParams().setConnectionManagerTimeout(defaultHttpConnectionManagerTimeout);
// 		PostMethod pmethod = new PostMethod("http://"+requestUrl);
 		PostMethod pmethod = new PostMethod(requestUrl);
 		NameValuePair[] nvps = new NameValuePair[params.size()];
 		Set<String> keys1 = params.keySet();
 		int i = 0;
 		for(String name1:keys1){
 			NameValuePair p = new NameValuePair(name1,params.get(name1));
 			nvps[i] = p;
 			i++;
 		}
 		pmethod.setRequestBody(nvps);
 		pmethod.getParams().setContentCharset("UTF-8");
		try {
			httpclient.executeMethod(pmethod);
			if(pmethod.getStatusCode()!=200){
				return null;
			}
			String resultStr = pmethod.getResponseBodyAsString();
			return resultStr;
		} catch (HttpException e) {
			e.printStackTrace();return null;
		} catch (IOException e) {
			e.printStackTrace();return null;
		}finally{
			 pmethod.releaseConnection();
		}
    }
    
    
    /**
     * POST带参数请求
     * @param requestUrl
     * @param paramsStr
     * @return
     */
    public String executePostReq1(String requestUrl,String paramsStr){
    	HttpClient httpclient = new HttpClient(connectionManager);
        httpclient.getParams().setConnectionManagerTimeout(defaultHttpConnectionManagerTimeout);
 		PostMethod pmethod = new PostMethod(requestUrl);
 		pmethod.setRequestBody(paramsStr);
 		pmethod.getParams().setContentCharset("UTF-8");
 		pmethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
 		pmethod.addRequestHeader("Content-Type","text/html;charset=utf-8");
		try {
			httpclient.executeMethod(pmethod);
			if(pmethod.getStatusCode()!=200){
				return null;
			}
			String resultStr = pmethod.getResponseBodyAsString();
			return resultStr;
		} catch (HttpException e) {
			e.printStackTrace();return null;
		} catch (IOException e) {
			e.printStackTrace();return null;
		}finally{
			 pmethod.releaseConnection();
		}
    }
   
}

  测试方法

	public static void main(String[] args) throws SOAPException, Exception {
		
		Map<String, String> params = new HashMap<String, String>();
		params.put("a","1");

		String string="http://xxx/xxx";
		
		/** *************以下是HTTP请求***************** */
//	    HttpProtocolHandler httpProtocolHandler  = HttpProtocolHandler.getInstance();; 
	    
//	    System.out.println(httpProtocolHandler.executePostReq(string, params));
	    
//		System.out.println(string);
//		System.out.println(httpProtocolHandler.executeGetString(string));
	}

  

posted @ 2015-05-07 10:15  同心圆gt  阅读(256)  评论(0编辑  收藏  举报