import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HttpRequest {
/**
* Options MultThreadedHttpConnectionManager参数配置:
* connectionStaleCheckingEnabled
* :这个标志对所有已经创建的connections都适用。除特殊情况外,此值应该设置成true。
* maxConnectionsPerHost:最大连接数,默认是2。 maxTotalConnections:最大活动连接数,默认是20。
*
* GET:200 POST:201 PUT:202 DELETE:200
*/
private final Logger LOGGER = LoggerFactory.getLogger(HttpRequest.class);
private String url = "http://XXXXX.com:88";// 请求URL
private String method = "GET";// 请求方式
private Map<String, String> paramMap = new HashMap<String, String>();
private int socketTimeout = 10000;// SOCKET超时
private int connTimeout = 5000;// 连接超时
/**
* 构造函数
*/
public HttpRequest() {
}
/**
* 添加参数
*
* @param key
* @param value
* @param first
*/
public void addData(String key, String value, boolean first) {
if (first) {
this.url = this.url.concat("?" + key + "=" + value);
} else {
this.url = this.url.concat("&" + key + "=" + value);
}
}
public void addParam(String key, String value) {
paramMap.put(key, value);
}
public void addMap(Map<String,String> fields){
Iterator<Entry<String, String>> it=fields.entrySet().iterator();
while(it.hasNext()){
Entry<String, String> map=it.next();
try {
paramMap.put(map.getKey(), URLEncoder.encode(map.getValue(),"utf-8"));
} catch (UnsupportedEncodingException e) {
}
}
}
/**
* 添加URL
*
* @param key
* @param value
*/
public void addURL(String key, String value) {
this.url = this.url.concat("/" + key + "/" + value);
}
/**
* 添加操作方式
*
* @param action
*/
public void addAction(String action) {
this.url = this.url.concat("/" + action);
}
/**
* 发送请求
*/
public String Send() {
if (this.method.equals("POST")) {
return SendPost(this.url);
} else if (this.method.equals("GET")) {
return SendGet(this.url);
} else if (this.method.equals("PUT")) {
return SendPut(this.url);
} else if (this.method.equals("DELETE")) {
return SendDelete(this.url);
}
return "";
}
/**
* 发送GET请求
*
* @param urlstr
* @return
*/
public String SendGet(String urlstr) {
HttpClient httpClient = new HttpClient(
new MultiThreadedHttpConnectionManager());
httpClient.getParams().setIntParameter("http.socket.timeout",
this.socketTimeout);
httpClient.getParams().setIntParameter("http.connection.timeout",
this.connTimeout);
GetMethod http = new GetMethod(urlstr);
String response = null;
try {
httpClient.executeMethod(http);
if (http.getStatusCode() != HttpStatus.SC_INTERNAL_SERVER_ERROR) {
response = http.getResponseBodyAsString();
} else {
LOGGER.error("HTTP Request to SAAS StatusCode: " + Integer.toString(http.getStatusCode()));
}
} catch (IOException e) {
LOGGER.error(e.getMessage());
} finally {
http.releaseConnection();
}
return response;
}
/**
* 发送POST请求
*
* @param urlstr
* @return
*/
public String SendPost(String urlstr) {
HttpClient httpClient = new HttpClient(
new MultiThreadedHttpConnectionManager()); //创建一个客户端,类似打开浏览器
httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
httpClient.getParams().setIntParameter("http.socket.timeout",
this.socketTimeout);
httpClient.getParams().setIntParameter("http.connection.timeout",
this.connTimeout);
PostMethod http = new PostMethod(urlstr); //创建post方法,类似输入地址
if(!paramMap.isEmpty()) {
for(Map.Entry<String, String> entry: paramMap.entrySet()) {
http.addParameter(entry.getKey(), entry.getValue());
}
}
String response = null;
long start = System.currentTimeMillis();
boolean isSuccess = true;
try {
httpClient.executeMethod(http); //执行url,类似按下回车键,发出请求
if (http.getStatusCode() != HttpStatus.SC_INTERNAL_SERVER_ERROR) {
response = http.getResponseBodyAsString();
} else {
LOGGER.error("HTTP Request to SAAS StatusCode: " + Integer.toString(http.getStatusCode()));
}
} catch (IOException e) {
LOGGER.error(e.getMessage());
isSuccess = false;
} finally {
http.releaseConnection();
}
String status = "FAILURE";
String statusCode = "null";
if(isSuccess) {
status = "SUCCESS";
statusCode = String.valueOf(http.getStatusCode());
}
String httpLogger = "HttpRequest " + status + ":\" 'method=Post"
+ "', 'statusCode=" + statusCode
+ "', 'url=" + urlstr
+ "', 'paramMap=" + paramMap
+ "', 'response=" + response
+ "', 'usedTime=" + (System.currentTimeMillis()-start) + "ms'\"";
LOGGER.warn(httpLogger);
return response;
}
/**
* 发送PUT请求
*
* @param urlstr
* @return
*/
public String SendPut(String urlstr) {
HttpClient httpClient = new HttpClient(
new MultiThreadedHttpConnectionManager());
httpClient.getParams().setIntParameter("http.socket.timeout",
this.socketTimeout);
httpClient.getParams().setIntParameter("http.connection.timeout",
this.connTimeout);
PutMethod http = new PutMethod(urlstr);
String response = null;
try {
httpClient.executeMethod(http);
if (http.getStatusCode() != HttpStatus.SC_INTERNAL_SERVER_ERROR) {
response = http.getResponseBodyAsString();
} else {
LOGGER.error("HTTP Request to SAAS StatusCode: " + Integer.toString(http.getStatusCode()));
}
} catch (IOException e) {
LOGGER.error(e.getMessage());
} finally {
http.releaseConnection();
}
return response;
}
/**
* 发送DELETE请求
*
* @param urlstr
* @return
*/
public String SendDelete(String urlstr) {
HttpClient httpClient = new HttpClient(
new MultiThreadedHttpConnectionManager());
httpClient.getParams().setIntParameter("http.socket.timeout",
this.socketTimeout);
httpClient.getParams().setIntParameter("http.connection.timeout",
this.connTimeout);
DeleteMethod http = new DeleteMethod(urlstr);
String response = null;
try {
httpClient.executeMethod(http);
if (http.getStatusCode() != HttpStatus.SC_INTERNAL_SERVER_ERROR) {
response = http.getResponseBodyAsString();
} else {
LOGGER.error("HTTP Request to SAAS StatusCode: " + Integer.toString(http.getStatusCode()));
}
} catch (IOException e) {
LOGGER.error(e.getMessage());
} finally {
http.releaseConnection();
}
return response;
}
/**
* 设置请求URL
*
* @param url
*/
public void setURL(String url) {
this.url = url;
}
/**
* 设置请求方式
*
* @param post
*/
public void setMethod(String post) {
this.method = post;
}
/**
* 设置SOCKET超时
*
* @param socketTimeout
*/
public void setSocketTimeout(int socketTimeout) {
this.socketTimeout = socketTimeout;
}
/**
* 设置连接超时
*
* @param
*/
public void setConnTimeout(int connTimeout) {
this.connTimeout = connTimeout;
}
}