公司内部的一个工具类实现Restful风格的资源获取
import com.keycenter.client.HmacClient;
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpStatus;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.DeserializationConfig.Feature;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.util.CollectionUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* Restful风格的资源获取
*/
public class RestFulUtil {
/**logger*/
private static final Logger LOGGER = LoggerFactory.getLogger(
com.bioperation.common.util.RestFulUtil.class);
/** json mapper */
private static final ObjectMapper mapper = new ObjectMapper();
private static final String APPLICATION_JSON = "application/json";
/**
* buc授权key
*/
// private static String apiKey;
/**
* 秘钥信息
*/
//private static String secretKey;
/**
* buc服务
*/
private static HmacClient client;
/**初始化配置*/
static {
//设置输入时忽略JSON字符串中存在而Java对象实际没有的属性
mapper.getDeserializationConfig().set(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
/**
* 执行Get请求,返回数据。
*
* @param para
* @param url
* @param connectTimeOut http连接超时时间 , s
* @param soTimeOut so socket连接超时时间 s
* @return
*/
public static String executeBucGet(Map para, String url,
Integer connectTimeOut, Integer soTimeOut, String apiKey,
String secretKey) {
try {
client = new HmacClient(apiKey, secretKey, Version.V1);
LoggerUtil.info(LOGGER, "Initialization BUC connection success");
} catch (Exception e) {
LOGGER.fatal("Initialize the buc connection fails", e);
}
try {
String params = com.buc.keycenter.common.util.HttpClientUtils
.encodeParams(para);
String reqUrl = url + "?" + params;
String result = client.get(reqUrl);
LoggerUtil.debug(LOGGER, "【 Call BUC】execute buc get call:reqUrl:" + reqUrl + ",result:"
+ result);
return result;
} catch (Exception e) {
LOGGER.error("【Call BUC】Perform buc call fails", e);
return null;
}
}
/**
* 执行Post restful资源请求
*
* @param
* @param c
* @param para
* @param url
* @return
*/
public static T executeBucGet(Class c, Map para, String url,
String apiKey, String secretKey) {
String body = executeBucGet(para, url, 18, 15, apiKey, secretKey);
if (body == null || body.length() < 1) {
return null;
}
//执行http访问
try {
T jsonToObject = jsonToObject(body, c);
LoggerUtil.info(LOGGER, "Convert to object【" + jsonToObject + "】");
return jsonToObject;
} catch (Exception e) {
LOGGER.error("Access 【" + url + "】to get data exception, result=" + body, e);
}
return null;
}
/**
* 执行Post restful资源请求
*
* @param
* @param c
* @param para
* @param url
* @param connectTimeOut 超时时间
* @return
*/
public static T executeBucGet(Class c, Map para, String url,
Integer connectTimeOut, String apiKey, String secretKey) {
String body = executeBucGet(para, url, connectTimeOut, connectTimeOut, apiKey, secretKey);
LoggerUtil.info(LOGGER, "请求buc返回结果:", body);
if (body == null || body.length() < 1) {
return null;
}
//执行http访问
try {
T jsonToObject = jsonToObject(body, c);
LoggerUtil.info(LOGGER, "Convert to object【" + jsonToObject + "】");
return jsonToObject;
} catch (Exception e) {
LOGGER.error("Access 【" + url + "】to get data exception, result=" + body, e);
}
return null;
}
public static T executeBucPost(Class c, Map para, String url,
String apiKey, String secretKey) {
try {
client = new HmacClient(apiKey, secretKey, Version.V1);
LoggerUtil.info(LOGGER, "Initialization BUC connection success");
} catch (Exception e) {
LOGGER.fatal("Initialize the buc connection fails", e);
}
//执行http访问
try {
String body = client.post(url, ClassCastUtils.castMapStringToMapList(para));
LoggerUtil.info(LOGGER,"POST BUC Result:", body);
if (StringUtil.isNotBlank(body)) {
if (StringUtil.contains(body, "null")) {
body = StringUtil.replace(body, "null", "\\\"\\\"");
}
LoggerUtil.info(LOGGER, "According to the【" + url + "】get http return data【" + body
+ "】 success");
T jsonToObject = jsonToObject(body, c);
LoggerUtil.info(LOGGER, "Convert to object【" + jsonToObject + "】");
return jsonToObject;
} else {
LOGGER.error("From 【" + url + "】get http return data is null ");
return null;
}
} catch (Exception ex) {
LOGGER.error("Access 【" + url + "】exception", ex);
}
return null;
}
/**
* 执行Get restful资源请求
*
* @param
* @param c
* @param para
* @param url
* @return
*/
public static T executeGet(Class c, Map para, String url,Map requestHeaders) {
HttpClient httpClient = new HttpClient();
//默认超时时间设置为8s
httpClient.getParams().setConnectionManagerTimeout(8000);
httpClient.getParams().setSoTimeout(5000);
HttpMethod httpMethod = new GetMethod(url);
//设置查询参数
if (!CollectionUtils.isEmpty(para)) {
List paras = new ArrayList();
Set> entrySet = (Set) para.entrySet();
for (Entry entry : entrySet) {
String val = entry.getValue() == null ? null : entry.getValue().toString();
paras.add(new NameValuePair(entry.getKey(), val));
}
httpMethod.setQueryString(paras.toArray(new NameValuePair[paras.size()]));
}
//设置请求头
if (!CollectionUtils.isEmpty(requestHeaders)) {
Set> entrySet = (Set) requestHeaders.entrySet();
for (Entry entry : entrySet) {
String val = entry.getValue() == null ? null : entry.getValue().toString();
httpMethod.setRequestHeader(entry.getKey(),val);
}
}
//执行http访问
try {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Execute http get request, url" + url + ", para: " + para);
}
int returnCode = httpClient.executeMethod(httpMethod);
if (returnCode == HttpStatus.SC_OK) {
String body = httpMethod.getResponseBodyAsString();
if (StringUtil.isBlank(body)) {
LOGGER.error("can not get data from url:" + url);
return null;
}
if (LOGGER.isInfoEnabled()) {
LOGGER.info("get data body from url : " + url + ", response body:" + body);
}
T jsonToObject = jsonToObject(body, c);
if (LOGGER.isInfoEnabled()) {
LOGGER.info("convert body to object: " + jsonToObject);
}
return jsonToObject;
} else {
LOGGER.error("request error, url:" + url + ", code=" + returnCode);
}
} catch (HttpException e) {
LOGGER.error("request error, " + url + ", client exception", e);
} catch (IOException e) {
LOGGER.error("request error, " + url + ", IO exception", e);
} catch (Exception e) {
LOGGER.error("request error, " + url + ", get data error", e);
}
return null;
}
/**
* 执行rest的post请求
*
* @param c
* @param para
* @param url
* @return
*/
public static T executePost(Class c, Map para, String url,
Map jsonPostPara,Map requestHeaders) {
HttpClient httpClient = new HttpClient();
//默认超时时间设置为8s
httpClient.getParams().setConnectionManagerTimeout(8000);
httpClient.getParams().setSoTimeout(5000);
PostMethod post = new PostMethod(url);
post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
//执行json的post参数封装
if (!CollectionUtils.isEmpty(jsonPostPara)) {
post.setRequestHeader(HttpHeaders.CONTENT_TYPE, APPLICATION_JSON);
try {
String postJsonStr = JSONObject.fromObject(jsonPostPara).toString();
RequestEntity se = new StringRequestEntity(postJsonStr, APPLICATION_JSON, "utf-8");
post.setRequestEntity(se);
} catch (Exception e) {
LOGGER.error("execute post json failed, params:" + jsonPostPara);
}
}
//设置请求头
if (!CollectionUtils.isEmpty(requestHeaders)) {
Set> entrySet = (Set) requestHeaders.entrySet();
for (Entry entry : entrySet) {
String val = entry.getValue() == null ? null : entry.getValue().toString();
post.setRequestHeader(entry.getKey(),val);
}
}
//设置post参数
if (!CollectionUtils.isEmpty(para)) {
List paras = new ArrayList();
Set> entrySet = (Set) para.entrySet();
for (Entry entry : entrySet) {
String val = entry.getValue() == null ? null : entry.getValue().toString();
paras.add(new NameValuePair(entry.getKey(), val));
}
post.setRequestBody(paras.toArray(new NameValuePair[paras.size()]));
}
//执行http访问
try {
int returnCode = httpClient.executeMethod(post);
if (returnCode == HttpStatus.SC_OK) {
String body = post.getResponseBodyAsString();
if (StringUtil.isBlank(body)) {
LOGGER.error("get empty body from url:" + url);
return null;
}
if (StringUtil.contains(body, "null")) {
body = StringUtil.replace(body, "null", "\\\"\\\"");
}
if (LOGGER.isInfoEnabled()) {
LOGGER.info("get body from url:" + url + ", body:" + body);
}
T jsonToObject = jsonToObject(body, c);
if (LOGGER.isInfoEnabled()) {
LOGGER
.info("convert body to object, body:" + body + ", object:" + jsonToObject);
}
return jsonToObject;
} else {
LOGGER.error("unkown status from url:" + url + ", status:" + returnCode);
}
} catch (Exception ex) {
LOGGER.error("request error url:" + url, ex);
}
return null;
}
/**
* 执行rest的put请求
* @param c
* @param url
* @return
*/
public static T executePut(Class c, String url, Map jsonPutPara, Map requestHeaders) {
HttpClient httpClient = new HttpClient();
//默认超时时间设置为8s
httpClient.getParams().setConnectionManagerTimeout(8000);
httpClient.getParams().setSoTimeout(5000);
PutMethod put = new PutMethod(url);
put.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
//执行json的post参数封装
if (!CollectionUtils.isEmpty(jsonPutPara)) {
put.setRequestHeader(HttpHeaders.CONTENT_TYPE, APPLICATION_JSON);
try {
String postJsonStr = JSONObject.fromObject(jsonPutPara).toString();
RequestEntity se = new StringRequestEntity(postJsonStr, APPLICATION_JSON, "utf-8");
put.setRequestEntity(se);
} catch (Exception e) {
LOGGER.error("executePut execute put json failed, params:" + jsonPutPara);
}
}
//设置请求头
if (!CollectionUtils.isEmpty(requestHeaders)) {
Set> entrySet = (Set) requestHeaders.entrySet();
for (Entry entry : entrySet) {
String val = entry.getValue() == null ? null : entry.getValue().toString();
put.setRequestHeader(entry.getKey(), val);
}
}
//执行http访问
try {
int returnCode = httpClient.executeMethod(put);
String body = put.getResponseBodyAsString();
if (returnCode == HttpStatus.SC_OK) {
if (StringUtil.isBlank(body)) {
LOGGER.error("executePut get empty body from url:" + url);
return null;
}
if (LOGGER.isInfoEnabled()) {
LOGGER.info("executePut get body from url:" + url + ", body:" + body);
}
T jsonToObject = jsonToObject(body, c);
if (LOGGER.isInfoEnabled()) {
LOGGER
.info("executePut convert body to object, body:" + body + ", object:" + jsonToObject);
}
return jsonToObject;
} else {
LOGGER.error("executePut unkown status from url:" + url + ", status:" + returnCode + "responseBody = " + body);
}
} catch (Exception ex) {
LOGGER.error("executePut request error url:" + url, ex);
}
return null;
}
/**
* 从json格式反序列化回java object对象
*
* @param jsonStr
* @param clazz
* @return
* @throws IOException
* @throws JsonMappingException
* @throws JsonParseException
*/
private static T jsonToObject(String jsonStr, Class clazz) throws Exception {
if (String.class.equals(clazz)) {
return (T) jsonStr;
}
return mapper.readValue(jsonStr, clazz);
}
}