spring+httpClient调用别人服务(一)

2014-11-24 07:34:32 · 作者: · 浏览: 4

首先,在spring的配置需要调用的url,例如:
[java]



在Manger调用的时候set注入进来

[java]
private List getData() throws Exception{
Map paraMap = new HashMap();
paraMap.put("action", "max_team_five_city_hotel_team_info");
String result = httpClientUtilManager.executeHttpRequestByGetType(groupProductUrl, paraMap);
List groupProducts = convertData(result);
return groupProducts;
}

executeHttpRequestByGetType方法:
[java]
/**
* get方式提交
*
* @param url
* @param keyValueMap
* @return
*/
public String executeHttpRequestByGetType(String url, Map keyValueMap) {
HttpClient client = new HttpClient();
StringBuffer sb = new StringBuffer(url);
PostMethod postMethod = null;
try {
//设置请求参数
if (keyValueMap != null) {
Iterator it = keyValueMap.entrySet().iterator();
if (keyValueMap.size() > 0) {
sb.append(" ");
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
sb.append(entry.getKey() + "=" + entry.getValue() + "&");
}
sb.deleteCharAt(sb.length()-1);
}

}
postMethod = new PostMethod(sb.toString());
log.debug("query uri ===============" + postMethod.getURI());
postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "gbk");
//todo:设置超时时间
postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 200000);
int statusCode = client.executeMethod(postMethod);
if (statusCode != HttpStatus.SC_OK) {
log.info("request '" + url + "' failed,the status is not 200,status:" + statusCode);
return "";
}
String responseBody = postMethod.getResponseBodyAsString();
return responseBody;
} catch (Exception e) {
log.error("发生异常!请检查网络和参数", e);
} finally {
if(postMethod!=null){
postMethod.releaseConnection();
}
}
return null;
}
}

convertData方法:
[java]
private List convertData(String result) throws Exception{
List groupProducts = new ArrayList();
if(result==null || "".equals(result)){
return groupProducts;
}
try {
ArrayList hashMaps = (ArrayList) JSONUtil.deserialize(result);
for (HashMap map : hashMaps) {
GroupProduct groupProduct = new GroupProduct();
groupProduct.setCityName(map.get("hotel_city").toString());
groupProduct.setDesc(map.get("title").toString());
groupProduct.setOldPrice(map.get("market_price").toString());
groupProduct.setPrice(map.get("team_price").toString());
groupProduct.setImgUrl(map.get("image").toString());
groupProduct.setProductUrl("team-" + map.get("id").toString() + ".html");
groupProduct.setDisCount(countDis(Double