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; } }
相关推荐
Kafka 2020-09-18
Wepe0 2020-10-30
杜倩 2020-10-29
windle 2020-10-29
minerd 2020-10-28
mengzuchao 2020-10-22
Junzizhiai 2020-10-10
bxqybxqy 2020-09-30
风之沙城 2020-09-24
kingszelda 2020-09-22
大唐帝国前营 2020-08-18
yixu0 2020-08-17
TangCuYu 2020-08-15
xiaoboliu00 2020-08-15
songshijiazuaa 2020-08-15
xclxcl 2020-08-03
zmzmmf 2020-08-03
newfarhui 2020-08-03
likesyour 2020-08-01