现在的位置: 首页 > 综合 > 正文

httpClient 用于发送HTTP请求的工具类

2018年02月01日 ⁄ 综合 ⁄ 共 5874字 ⁄ 字号 评论关闭
package util;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;


/**
 * 用于发送HTTP请求的工具类
 * 
 * @author * 
 */
public class HttpClientUtil {


	private String requestURL;
	private int connectionTimeout;
	private int timeout;

	public HttpClientUtil() {
		requestURL = "";
		connectionTimeout = Constant.CONNECTION_TIME_OUT;
		timeout = Constant.TIME_OUT;
	}

	public HttpClientUtil(String requestURL) {
		this.requestURL = requestURL;
		connectionTimeout = Constant.CONNECTION_TIME_OUT;
		timeout = Constant.TIME_OUT;
	}

	public HttpClientUtil(String requestURL, int connectionTimeout, int timeout) {
		this.requestURL = requestURL;
		this.connectionTimeout = connectionTimeout;
		this.timeout = timeout;
	}
	
	/**
	 * @throws Exception
	 * @throws TimeOutExcetipion
	 * @throws ConnetcionTimeOutException
	 */
	public String sendToBoss() {
		// long begin = System.currentTimeMillis();
		HttpClient client = new HttpClient();
		String result = "";
		
		PostMethod method =null;
		// method.setRequestHeader("Connection", "close");
		
		try {
			//ByteArrayRequestEntity entity = new ByteArrayRequestEntity(xml.getBytes("utf-8"));
			method = new PostMethod(requestURL);
			//method.setRequestEntity(entity);
			method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
			// 设置请求包头文件
			method.setRequestHeader("Content-Type", "text/xml;charset=utf-8");
			//method.setRequestHeader("Content-Length", String.valueOf(entity.getContentLength()));
			client.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);
			client.getHttpConnectionManager().getParams().setSoTimeout(timeout);
			 client.executeMethod(method);
			//System.out.println(statusCode);
			result = readStream(method.getResponseBodyAsStream(), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (HttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			method.releaseConnection();
			client.getHttpConnectionManager().closeIdleConnections(0);
		}

		return result;
	}
	

	/**
	 * @throws Exception
	 * @throws TimeOutExcetipion
	 * @throws ConnetcionTimeOutException
	 */
	public String sendToBoss(String xml) {
//		log.debug("发送XML请求文件:"+xml);
		// long begin = System.currentTimeMillis();
		HttpClient client = new HttpClient();
		String result = "";
		
		PostMethod method =null;
		// method.setRequestHeader("Connection", "close");
		
		try {
			ByteArrayRequestEntity entity = new ByteArrayRequestEntity(xml.getBytes("utf-8"));
			method = new PostMethod(requestURL);
			method.setRequestEntity(entity);
			method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
			// 设置请求包头文件
			method.setRequestHeader("Content-Type", "text/xml;charset=utf-8");
			method.setRequestHeader("Content-Length", String.valueOf(entity.getContentLength()));
			client.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);
			client.getHttpConnectionManager().getParams().setSoTimeout(timeout);
			 client.executeMethod(method);
			//System.out.println(statusCode);
			result = readStream(method.getResponseBodyAsStream(), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (HttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			method.releaseConnection();
			client.getHttpConnectionManager().closeIdleConnections(0);
		}

		return result;
	}
	
	public InputStream sendToBossRStream(String xml) throws Exception {
		HttpClient client = new HttpClient();
		
		PostMethod method = new PostMethod(requestURL);
		// method.setRequestHeader("Connection", "close");
		ByteArrayRequestEntity entity = new ByteArrayRequestEntity(xml.getBytes("utf-8"));
		try {
			
			// RequestEntity entity = new StringRequestEntity(xml, "text/xml",
			// "utf-8");
			method.setRequestEntity(entity);
		
			method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
			// 设置请求包头文件
			method.setRequestHeader("Content-Type", "text/xml;charset=utf-8");
		//	System.out.println("发送XML文件请求长度:===========:"+String.valueOf(entity.getContentLength()));
			method.setRequestHeader("Content-Length", String.valueOf(entity.getContentLength()));
			client.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);
			client.getHttpConnectionManager().getParams().setSoTimeout(timeout);
			int statusCode= client.executeMethod(method);
			//System.out.println(statusCode);
			return method.getResponseBodyAsStream();
			
		} catch (HttpException e) {
			e.printStackTrace();
			
			//throw new Exception("java.net.SocketTimeoutException: Read timed out");
		} catch (IOException e) {
			e.printStackTrace();
			
			//throw new Exception("java.net.SocketException: Connection reset");
		} finally {
			method.releaseConnection();
			client.getHttpConnectionManager().closeIdleConnections(0);
			// ((SimpleHttpConnectionManager)client.getHttpConnectionManager()).shutdown();
		}
		return null;
	}

	public static String readStream(InputStream in, String charset) throws IOException {
		StringBuilder buf = new StringBuilder();
		int ch = -1;
		Reader reader = new InputStreamReader(new BufferedInputStream(in), charset);
		while (-1 != (ch = reader.read())) {
			buf.append((char) ch);
		}
		return buf.toString();
	}

	public int getConnectionTimeout() {
		return connectionTimeout;
	}

	public void setConnectionTimeout(int connectionTimeout) {
		this.connectionTimeout = connectionTimeout;
	}

	public int getTimeout() {
		return timeout;
	}

	public void setTimeout(int timeout) {
		this.timeout = timeout;
	}

	public String getRequestURL() {
		return requestURL;
	}

	public void setRequestURL(String requestURL) {
		this.requestURL = requestURL;
	}
	
	public static void main(String args[])
	{
		String url="http://localhost:8080/MOI/data/dataPub.do";
		HttpClientUtil shc = new HttpClientUtil(url);
		
	try {
			shc.sendToBoss("");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
}

抱歉!评论已关闭.