1. HttpClient工具类:
(1) 地址: taotao-common中HttpClientUtil.java
(2)方法:
doGet(String url, Map<String, String> param);
doGet(String url);
doPost(String url, Map<String, String> param);
doPost(String url);
doPostJson(String url, String json);
(3) 使用场景: 用来模拟浏览器的get和post请求
(5)使用例子: (地址com.taotao.portal.service.impl 中的 search(String queryString, int page))
请求端:
public SearchResult search(String queryString, int page) {
// 调用taotao-search的服务
// 查询参数
Map<String, String> param = new HashMap<>();
param.put("q", queryString);
param.put("page", page + "");
try {
// 调用服务
String json = HttpClientUtil.doGet(SEARCH_BASE_URL, param);
// 把字符串转换成java对象
TaotaoResult taotaoResult = TaotaoResult.formatToPojo(json, SearchResult.class);
if (taotaoResult.getStatus() == 200) {
SearchResult result = (SearchResult) taotaoResult.getData();
return result;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
接收端: com.taotao.search.controller
/**
* 商品查询Controller
* @author Administrator
*
*/
@Controller
public class SearchController {
@Resource
private SearchService searchServiceImpl;
@RequestMapping(value="/query",method=RequestMethod.GET)
@ResponseBody
public TaotaoResult search(@RequestParam("q")String queryString,
@RequestParam(defaultValue="1")Integer page,
@RequestParam(defaultValue="60")Integer rows) {
//查询条件不能为空
if (StringUtils.isBlank(queryString)) {
return TaotaoResult.build(400, "查询条件不能为空");
}
SearchResult searchResult = null;
try {
queryString = new String(queryString.getBytes("iso8859-1"), "utf-8");
searchResult = searchServiceImpl.search(queryString, page, rows);
} catch (Exception e) {
e.printStackTrace();
return TaotaoResult.build(500, ExceptionUtil.getStackTrace(e));
}
return TaotaoResult.ok(searchResult);
}
}