1. 什麼是RestTemplate
傳統情況下在java代碼裏訪問restful服務,一般使用Apache的HttpClient。不過此種方法使用起來太過繁瑣。spring提供了一種簡單便捷的模板類來進行操作,這就是RestTemplate。
2.使用方式
2.1導入依賴
<!--RestTemplate-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
2.2配置RestTemplate
@Configuration
public class RestTemplateConfig {
@Autowired
private RestTemplateBuilder builder;
@Bean
public RestTemplate restTemplate(){
return builder.build();
}
}
2.3引用並使用
service層(restfull提交方式)
@Service
@Slf4j
public class RequestURLServiceImpl {
//訪問地址:http://t.weather.sojson.com/api/weather/city/{city}
private static final String url = "http://t.weather.sojson.com/api/weather/city/";
@Autowired
private RestTemplate restTemplate; //此模板需要到config下配置
public String demo(String id){
String restTemplateForObject = restTemplate.getForObject(url+id, String.class);
//也可以使用下面這一行寫法直接將獲取的數據封裝到實體類中,前提是要有相對應的實體類
// User user = restTemplate.getForObject("https://www.XXX.com/", User.class);
log.info(restTemplateForObject);
return restTemplateForObject;
}
}
controller層
@Controller
@RequestMapping("/request")
@Slf4j
public class RequestController {
@Autowired
private RequestURLServiceImpl requestURLService;
@RequestMapping("/cityid/{cityid}")
@ResponseBody
public String getWeatherResponseById( @PathVariable("cityid") String cityid){
String str = requestURLService.demo(cityid);
return str;
}
}
訪問結果
3.Post提交方式
3.1環境 運行兩個項目 被調用者項目端口號爲8080 調用者端口號爲8085
3.2被調用者:只寫了一個controller如下
@RestController
public class Test {
//模擬post接口此方法將傳遞過來的的參數拼接然後返回
@PostMapping("/ppp")
public String p(@RequestParam("str01")String str01,@RequestParam("str02") String str02){
System.out.println("aaaaaaaaaaaaaa"+str01+str02);
return str01+str02;
}
}
3.2調用者:service代碼
@Service
@Slf4j
public class RequestURLServiceImpl implements RequestURLService {
@Autowired
private RestTemplate restTemplate; //此模板需要到config下配置
public String posturl(String str01 ,String str02){
String url = "http://localhost:8080/ppp";
//若是所需參數爲對象的話則將map換成實體類對象即可
MultiValueMap<String,Object> map = new LinkedMultiValueMap();
map.add("str01",str01);
map.add("str02",str02);
//返回值爲String
String restTemplateForObject = restTemplate.postForObject(url,map,String.class);
return restTemplateForObject;
}
}
3.2調用者:controller代碼
@Controller
@RequestMapping("/request")
@Slf4j
public class RequestController {
@PostMapping("/post")
@ResponseBody
public String posturl( String str01,String str02){
String str = requestURLService.posturl(str01, str02);
return str;
}
}
3.3測試結果