1、好的文章:
http://blog.youkuaiyun.com/wangpeng047/article/details/19624529
http://www.cnblogs.com/loveyakamoz/archive/2011/07/21/2113252.html
http://www.cnblogs.com/loveyakamoz/archive/2011/07/21/2112804.html
2.使用commons-httpclient封装的:需要导入commons-client.jar commons-logging.jar commons-codec.jar
(1)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
public class HttpUtil {
private static MultiThreadedHttpConnectionManager manager = new MultiThreadedHttpConnectionManager();
private static int maxConnectionPerHost = 15;
private static int maxTotalConnections = 40;
private static final int CONN_OUT_TIME = 10 * 1000;
private static final int SO_OUT_TIME = 240 * 1000;
// 初始化ConnectionManger的方法
public static void setPara(int timeout) {
manager.getParams().setConnectionTimeout(timeout);
manager.getParams().setSoTimeout(timeout);
manager.getParams().setDefaultMaxConnectionsPerHost(maxConnectionPerHost);
manager.getParams().setMaxTotalConnections(maxTotalConnections);
}
/**
* get请求,默认超时5s
*
* @param restUrl
* @param timeoutMillions
* @return
*/
public static String getResponseByHttp(String restUrl) {
String responseStr = null;
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(restUrl);
client.getHttpConnectionManager().getParams().setConnectionTimeout(CONN_OUT_TIME);
client.getHttpConnectionManager().getParams().setSoTimeout(SO_OUT_TIME);
method.setRequestHeader("rest-who", "aries");
method.setRequestHeader("rest-code", "ccc558986e26577ce68b579995bfa01a");
try {
client.executeMethod(method);
method.getParams().setContentCharset("UTF-8");
if (method.getStatusCode() == HttpStatus.SC_OK) {
responseStr = method.getResponseBodyAsString();
}
} catch (Exception e) {
// log.error("request out of time, CONN_OUT_TIME="+CONN_OUT_TIME+", SO_OUT_TIME="+SO_OUT_TIME+", URL="+restUrl,e);
}
method.releaseConnection();
return responseStr;
}
/**
* get请求
*
* @param url
* @param encode
* @param timeOut
* @return
*/
public static ResultDto<Integer, String> getGetResponseByHttp(String url, String encode, int timeout)
throws HttpException,
IOException {
HttpUtil.setPara(timeout);
HttpClient client = new HttpClient(manager);
GetMethod get = new GetMethod(url);
get.setFollowRedirects(true);
get.setRequestHeader("refer", "aries");
// 设置重试次数
get.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(1, false));
int responseCode = HttpStatus.SC_NOT_FOUND;
StringBuffer resultBuffer = new StringBuffer();
String resultStr = null;
try {
responseCode = client.executeMethod(get);
BufferedReader in = new BufferedReader(new InputStreamReader(get.getResponseBodyAsStream(),
get.getResponseCharSet()));
String inputLine = null;
while ((inputLine = in.readLine()) != null) {
resultBuffer.append(inputLine);
}
in.close();
resultStr = HttpUtil.ConverterStringCode(resultBuffer.toString(), get.getResponseCharSet(), encode);
} finally {
get.releaseConnection();
}
if (responseCode > HttpStatus.SC_OK) {
// logger.error("url: " + url + " get error! return code is: " + responseCode);
}
return new ResultDto<Integer, String>(responseCode, resultStr);
}
public static ResultDto<Integer, String> getPostResponseWithHttpClient(String url, String encode,
String requestData, int timeout,String type)
throws HttpException,
IOException {
HttpClient client = new HttpClient(manager);
HttpUtil.setPara(timeout);
// 设置参数
PostMethod mtd = new PostMethod(url);
if(type.contains("XML")){
mtd.setRequestEntity(new StringRequestEntity(requestData,"text/xml","utf-8"));
}else if (type.contains("JSON")){
mtd.setRequestEntity(new StringRequestEntity(requestData,"text/json","utf-8"));
}else{
mtd.setRequestEntity(new StringRequestEntity(requestData,null,"utf-8"));
}
int responseCode = HttpStatus.SC_NOT_FOUND;
String resultStr = null;
try {
responseCode = client.executeMethod(mtd);
BufferedReader in = new BufferedReader(new InputStreamReader(mtd.getResponseBodyAsStream(),
mtd.getResponseCharSet()));
String inputLine = null;
StringBuffer resultBuffer = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
resultBuffer.append(inputLine);
}
in.close();
resultStr = resultBuffer.toString();
resultStr = HttpUtil.ConverterStringCode(resultBuffer.toString(), mtd.getResponseCharSet(), encode);
} finally {
mtd.releaseConnection();
}
if (responseCode > HttpStatus.SC_OK) {
// logger.error("url: " + url + " get error! return code is: " + responseCode);
}
return new ResultDto<Integer, String>(responseCode, resultStr);
}
private static String ConverterStringCode(String source, String srcEncode, String destEncode) {
if (source != null) {
try {
return new String(source.getBytes(srcEncode), destEncode);
} catch (UnsupportedEncodingException e) {
return "";
}
} else {
return "";
}
}
}
(2)dto类
public class ResultDto<A,B> {
private A first;
private B second;
public ResultDto(A first,B second) {
this.first = first;
this.second = second;
}
public A getFirst() {
return first;
}
public void setFirst(A first) {
this.first = first;
}
public B getSecond() {
return second;
}
public void setSecond(B second) {
this.second = second;
}
}