一、添加依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
二、建立HttpClient . java类
主要代码如下:
@Service
public class HttpClient {
public AjaxResult ajaxResultClient(String url, HttpMethod method, String params){
RestTemplate client = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
// 请勿轻易改变此提交方式,大部分的情况下,提交方式都是表单提交
//headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.setContentType(MediaType.APPLICATION_PROBLEM_JSON_UTF8);
HttpEntity<String> requestEntity = new HttpEntity<String>(params, headers);
// 执行HTTP请求
ResponseEntity<AjaxResult> response = client.exchange(url, method, requestEntity, AjaxResult.class);
return response.getBody();
}
}
三、controller调用示例
@RequestMapping(value = "/c/save",method= RequestMethod.POST)
public AjaxResult packing(@RequestBody Map<String,Object> map){
//api url地址
String url = "http://127.0.0.1:8088/ml/p/a/save";
//post请求
HttpMethod method =HttpMethod.POST;
Map<String, Object> params= new HashMap<String, Object>();
params.put("batch", map.get("batch"));
params.put("num", map.get("num"));
String paramString =JSON.toJSONString(params);
//发送http请求并返回结果
return httpClient.ajaxResultClient(url,method,paramString);
}
@RequestMapping(value = "/c/a/p/getinfobybatch",method= RequestMethod.GET)
public AjaxResult getinfobybatch(@RequestParam("batch") String batch){
//api url地址
String url = "http://127.0.0.1:8088/m/p/a/getinfobybatch?batch="+batch;
HttpMethod method =HttpMethod.GET;
// 封装参数,千万不要替换为Map与HashMap,否则参数无法传递
Map<String, Object> params= new HashMap<String, Object>();
String paramString =JSON.toJSONString(params);
//发送http请求并返回结果
return httpClient.ajaxResultClient(url,method,paramString);
}