在http://www.cnblogs.com/ITtangtang/p/3968093.html的基础上封装了一下get和post请求的常用方法,
虽然很简单,也晒晒
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import java.util.Iterator;
import java.util.Map;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
/**
*
* @author zhang jinguang
* @version $Id: HttpInvoker.java, v 0.1 2016年10月26日 下午2:17:59 zhang jinguang
* Exp $
*/
public class HttpInvoker {
private static Log logger = LogFactory.getLog(HttpInvoker.class);
// 默认字符集编码
private final static String DEFAULT_CHARSET = "utf-8";
// 默认超时时间, 单位为毫秒(ms)
private final static int DEFAULT_TIMEOUT = 10000;
/**
* http的默认get请求,默认超时时间为10s,默认字符集为utf-8,如需定制,请调用
*
* @author zhang jinguang 2016年10月26日
* @param url:get请求的url地址,不要带参数,参数放到params里面
* @param params:请求的url需要的参数, 没有参数,直接传null
* @return
* @throws Exception
*/
public static String httpGet(String url, Map<?, ?> params) throws Exception {
return httpGet(url, params, DEFAULT_TIMEOUT, DEFAULT_CHARSET);
}
/**
* @author zhang jinguang 2016年10月26日
* @param url:get请求的url地址,不要带参数,参数放到params里面
* @param params
* @param timeout
* @param charset
* @return
* @throws Exception
*/
public static String httpGet(String url, Map<?, ?> params, int timeout, String charset) throws Exception {
return invokeGet(url, params, timeout, charset);
}
/**
* http post请求
*
* @author zhang jinguang 2016年10月26日
* @param url:请求的url
* @param params:post的内容
* @return
* @throws Exception
*/
public static String httpPost(String url, Map<?, ?> params) throws Exception {
return httpPost(url, params, DEFAULT_TIMEOUT, DEFAULT_CHARSET);
}
/**
* http post请求
*
* @author zhang jinguang 2016年10月26日
* @param url:请求的url
* @param params:post的内容
* @param timeout:超时时间
* @param charset:字符集
* @return
* @throws Exception
*/
public static String httpPost(String url, Map<?, ?> params, int timeout, String charset) throws Exception {
return invokePost(url, params, timeout, charset);
}
/**
* 实际的post请求
*
* @author zhang jinguang 2016年10月26日
* @param url:请求的url
* @param params:post的内容
* @param timeout:超时时间
* @param charset:字符集
* @return
* @throws Exception
*/
private static String invokePost(String url, Map<?, ?> params, int timeout, String charset) throws Exception {
logger.debug("HTTP调用POST[" + url + "][" + params + "]");
HttpMethod httpMethod = null;
if (params != null && params.size() > 0) {
Iterator<?> paramKeys = params.keySet().iterator();
httpMethod = new PostMethod(url);
NameValuePair[] form = new NameValuePair[params.size()];
int formIndex = 0;
while (paramKeys.hasNext()) {
String key = (String) paramKeys.next();
Object value = params.get(key);
if (value != null && value instanceof String && !value.equals("")) {
form[formIndex] = new NameValuePair(key, (String) value);
formIndex++;
} else if (value != null && value instanceof String[] && ((String[]) value).length > 0) {
NameValuePair[] tempForm = new NameValuePair[form.length + ((String[]) value).length - 1];
for (int i = 0; i < formIndex; i++) {
tempForm[i] = form[i];
}
form = tempForm;
for (String v : (String[]) value) {
form[formIndex] = new NameValuePair(key, (String) v);
formIndex++;
}
}
}
((PostMethod) httpMethod).setRequestBody(form);
}
return executeNetRequest(url, timeout, charset, httpMethod);
}
/**
* 拼接请求参数
*
* @author zhang jinguang 2016年10月26日
* @param url
* @param params
* @param timeout
* @param charset
* @return
* @throws Exception
*/
private static String invokeGet(String url, Map<?, ?> params, int timeout, String charset) throws Exception {
logger.debug("HTTP调用GET[" + url + "][" + params + "]");
HttpMethod httpMethod = null;
// 如果需要拼接请求参数
if (params != null && params.size() > 0) {
Iterator<?> paramKeys = params.keySet().iterator();
StringBuffer getUrl = new StringBuffer(url.trim());
if (url.trim().indexOf("?") > -1) {
if (url.trim().indexOf("?") < url.trim().length() - 1
&& url.trim().indexOf("&") < url.trim().length() - 1) {
getUrl.append("&");
}
} else {
getUrl.append("?");
}
while (paramKeys.hasNext()) {
String key = (String) paramKeys.next();
Object value = params.get(key);
if (value != null && value instanceof String && !value.equals("")) {
getUrl.append(key).append("=").append(value).append("&");
} else if (value != null && value instanceof String[] && ((String[]) value).length > 0) {
for (String v : (String[]) value) {
getUrl.append(key).append("=").append(v).append("&");
}
}
}
if (getUrl.lastIndexOf("&") == getUrl.length() - 1) {
httpMethod = new GetMethod(getUrl.substring(0, getUrl.length() - 1));
} else {
httpMethod = new GetMethod(getUrl.toString());
}
} else {// 没有请求参数
httpMethod = new GetMethod(url);
}
return executeNetRequest(url, timeout, charset, httpMethod);
}
/**
* 执行网络请求
*
* @author zhang jinguang 2016年10月26日
* @param url
* @param timeout
* @param charset
* @param httpMethod
* @return
* @throws SocketTimeoutException
* @throws ConnectException
* @throws Exception
*/
private static String executeNetRequest(String url, int timeout, String charset, HttpMethod httpMethod)
throws SocketTimeoutException, ConnectException, Exception {
HttpClient client = new HttpClient();
client.getParams().setSoTimeout(timeout);
client.getParams().setContentCharset(charset);
String result = "";
try {
client.executeMethod(httpMethod);
result = httpMethod.getResponseBodyAsString();
} catch (SocketTimeoutException e) {
logger.error("连接超时[" + url + "]");
throw e;
} catch (java.net.ConnectException e) {
logger.error("连接失败[" + url + "]");
throw e;
} catch (Exception e) {
logger.error("连接时出现异常[" + url + "]");
throw e;
} finally {
if (httpMethod != null) {
try {
httpMethod.releaseConnection();
} catch (Exception e) {
logger.error("释放网络连接失败[" + url + "]");
throw e;
}
}
}
return result;
}
}
参考博文:http://www.cnblogs.com/ITtangtang/p/3968093.html