首先maven引用httpclient3
<!-- httpclient -->
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
然后添加httpclient3 工具类
package com.suncar.common.util.http;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import com.suncar.common.entity.BaseRequest;
import com.suncar.common.util.MD5;
/**
* @ClassName HttpClient3
* @Description 请求接口公共@author erle
* @date 2014-4-17
* @version 1.0
*/
public class HttpClient3 extends BaseRequest{
public static final Logger logger = Logger.getLogger(HttpClient3.class);
private static final String DEFAULT_CHARSET ="UTF-8";
private static final int DEFAULT_CONNECTION_TIMEOUT = 120 * 1000;
private static final int DEFAULT_SOCKET_READ_TIMEOUT = 120 * 1000;
private String charset;
private int timeout;
public HttpClient3() {
this(DEFAULT_CHARSET, DEFAULT_SOCKET_READ_TIMEOUT);
}
public HttpClient3(int timeout) {
this(DEFAULT_CHARSET, timeout);
}
public HttpClient3(String charset, int timeout) {
this.charset = (charset==null||charset.length()==0)? DEFAULT_CHARSET : charset;
this.timeout = timeout < 0 ? DEFAULT_SOCKET_READ_TIMEOUT : timeout;
}
public String doPost(String url, Map<String, String> params) throws Exception {
return doPost(url, concatParameters(params));
}
public String doGet(String url, Map<String, String> params) throws Exception {
return doGet(url, concatParameters(params));
}
/**
* 发送https POST请求
*/
/* public String doPost(String url, Map<String, String> params) throws Exception {
HttpsClient httpsClient =new HttpsClient();
return httpsClient.doPost(url, params);
}*/
/**
* 发送POST请求
* @param url 请求
* @param params url编码的请求参 * @return
* @throws Exception
*/
public String doPost(String url, String params) throws Exception {
logger.info(" Http Post Url : " + url + " param : "+ params);
PostMethod post = null;
try {
HttpClient httpClient = new HttpClient();
post = new PostMethod(url);
// RequestEntity requestEntity = new StringRequestEntity(params, "application/x-www-form-urlencoded",this.charset);
RequestEntity requestEntity = new StringRequestEntity(params, "application/x-www-form-urlencoded",this.charset);
post.setRequestEntity(requestEntity);
post.setRequestHeader("Connection", "close");
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT);
httpClient.getHttpConnectionManager().getParams().setSoTimeout(this.timeout);
post.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false));
httpClient.executeMethod(post);
String resp = getResonseString(post);
return resp;
} catch (Exception e) {
throw e;
} finally {
post.releaseConnection();
}
}
public static String sortJoin(Map<String,String> dataMap){
List<Map.Entry<String, String>> list = new ArrayList<Map.Entry<String, String>>(
dataMap.entrySet());
Collections.sort(list,new Comparator<Map.Entry<String, String>>() {
public int compare(Entry<String, String> o1,
Entry<String, String> o2) {
String k1 = o1.getKey();
String k2 = o2.getKey();
return k1.compareTo(k2);
}
});
StringBuffer sb = new StringBuffer();
for(int i=0;i<list.size();i++) {
Map.Entry<String, String> data = list.get(i);
sb.append(data.getKey());
sb.append("=");
sb.append(data.getValue());
if(i<list.size()-1) {
sb.append("&");
}
}
return sb.toString();
}
public String doGet(String url, String params) throws Exception {
logger.info(" Http Get Url : " + url + " param : "+ params);
GetMethod get = null;
try {
url += "?"+params;
HttpClient httpClient = new HttpClient();
get = new GetMethod(url);
// get.addRequestHeader("fileName", "测试.jpg");
get.setRequestHeader("Connection", "close");
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT);
httpClient.getHttpConnectionManager().getParams().setSoTimeout(this.timeout);
get.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false));
httpClient.executeMethod(get);
String resp = getResonseString(get);
return resp;
} catch (Exception e) {
throw e;
} finally {
get.releaseConnection();
}
}
public InputStream downFile4PathIo(String url, String fileName) {
logger.info(" Http Get Url : " + url + " param : "+ fileName);
GetMethod get = null;
try {
fileName = URLEncoder.encode(fileName,"ISO-8859-1");
url += "?fileName="+fileName;
HttpClient httpClient = new HttpClient();
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT);
httpClient.getHttpConnectionManager().getParams().setSoTimeout(this.timeout);
get = new GetMethod(url);
get.addRequestHeader("fileName", fileName);
// get.setRequestHeader("Connection", "close");
get.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false));
httpClient.executeMethod(get);
InputStream in = get.getResponseBodyAsStream();
return in;
} catch (Exception e) {
e.printStackTrace();
} finally {
// get.releaseConnection();
}
return null;
}
/**
* 发送POST请求
* @param url 请求
* @param params url编码的请求参数
* @return
* @throws Exception
*/
private String getResonseString(HttpMethodBase post) throws Exception{
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream in = post.getResponseBodyAsStream();
byte[] bys = new byte[1024];
for(int n = -1; (n = in.read(bys)) != -1; ) {
out.write(bys, 0, n);
}
return new String(out.toByteArray(), this.charset);
}
public String concatParameters(Map<String, String> params) throws Exception {
params.put("source", "3");
params.put("version", "1");
params.put("timestamp", getTimestamp());
String paramStr = sortJoin(params);
String sign = MD5.encodeString(paramStr+"&SSDL");
paramStr += "&sign="+sign;
/*绑定加密因子结束*/
// StringBuilder sb = new StringBuilder();
// int p = 0;
// for (Map.Entry<String, String> entry : params.entrySet()) {
// if (p++ > 0) {
// sb.append('&');
// }
// sb.append(entry.getKey()).append('=').append(entry.getValue());
// }
// initTimesDigest(params);
// setDigest(MD5.encodeString(sb.toString()));
// sb.append("&sign=").append(getDigest());//.append("&SSDL");
return paramStr;
}
public String encodeURI(String param) {
if(param == null) {
return "";
}
try {
return URLEncoder.encode(param, this.charset);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return "";
}
public String getCharset() {
return charset;
}
public void setCharset(String charset) {
this.charset = charset;
}
public int getTimeout() {
return timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
}
最后就可以进行单元测试了,可以按如下方法写
public class HttpTest {
@Test
public void login() throws Exception{
HttpClient3 httpClient = new HttpClient3();
Map<String , String> params = new HashMap<String, String>();
params.put("user", "18816998693");
params.put("pwd", "123456");
String responseStr = httpClient.doPost("http://192.168.2.130:8090/api/login", params);
System.out.println(responseStr);
}
}