http请求与响应工具类

 

 对于http的请求与响应,可以使用commons-httpclient.jar来实现数据的接收与发送,代码如下:
package com.project.util;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

/**
 * Http请求公共类
 * @author Administrator
 *
 */
public class HttpPost {
	private static HttpClient httpclient = null;
	private static int iTimeOut = 5000;
	@SuppressWarnings("rawtypes")
	private static Map map = new HashMap();
	private static final Object object = new Object();
	private String postUrl = null;
	
	private HttpPost() {
		
	}
	
	public static HttpPost getInstance(String sUrl) {
		HttpPost instance = null;
		if((instance = (HttpPost) map.get(sUrl)) == null) {
			synchronized (object) {
				if((instance = (HttpPost)map.get(sUrl)) == null) {
					if(httpclient == null) {
						MultiThreadedHttpConnectionManager manager = new MultiThreadedHttpConnectionManager();
						httpclient = new HttpClient(manager);
					}
					instance = new HttpPost();
					instance.postUrl = sUrl;
				}
			}
		}
		return instance;
	}
	
	public String post(Map map) {
		return post(map, "application/x-www-form-urlencoded", "Mozilla/4.0");
	}	
	
	public String post(Map map, String contentType, String userAgent) {
		if(iTimeOut >= 0) {
			httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(iTimeOut);
		} else {
			httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(0);
		}
		PostMethod method = new PostMethod(postUrl);
		method.addRequestHeader("Content-Type", contentType);
		method.addRequestHeader("User-Agent", userAgent);
		// 处理需要发送的字符串
		NameValuePair[] valuePairs = new NameValuePair[map.size()];
		Collection collection = map.entrySet();
		Iterator iterator = collection.iterator();
		int i = 0;
		while(iterator.hasNext()) {
			String strKey = ((Map.Entry)iterator.next()).getKey().toString();
			valuePairs[(i++)] = new NameValuePair(strKey, (String)map.get(strKey));
		}
		method.setRequestBody(valuePairs);
		String responseStr = "";
		try {
			httpclient.executeMethod(method);
			String charSet = method.getResponseCharSet();
			responseStr = new String(method.getResponseBodyAsString().getBytes(charSet), "ISO8859-1");
		} catch(Exception e) {
			e.printStackTrace();
		}
		return responseStr;
	}
}

 

你可能感兴趣的:(Http请求与响应)