本文介紹restTemplate基礎用法。
Java中get和post的用法請參考:Java中Get和Post的使用
1 提供get/post接口
1.1 Controller
@RestController
@RequestMapping("/homepage")
public class MyController {
@Autowired
MyService myService;
// 提供get接口
@GetMapping("/provideGet")
public Map{
return myService.provideGet();
}
// 提供post接口
@PostMapping("/providePost")
public Map{
return myService.providePost(number, name);
}
// 提供map參數的post接口
@PostMapping("/providePostByMap")
public Map{
return myService.providePostByMap(map);
}
// 調用get接口
@GetMapping("/useGet")
public Map{
return myService.useGet();
}
}
1.2 Service
@Service
@EnableScheduling
public class MyService {
public Map{
Map
2 調用get/post接口
使用restTemplate調用get/post接口。
getForObject()
:返回值是HTTP
協議的響應體getForEntity()
:返回的是ResponseEntity
,ResponseEntity
是對HTTP
響應的封裝,除了包含響應體,還包含HTTP
狀態碼、contentType、contentLength、Header
等信息
2.1 Controller
@RestController
@RequestMapping("/homepage")
public class MyController {
@Autowired
MyService myService;
// 調用get接口
@GetMapping("/useGet")
public Map{
return myService.useGet();
}
// 調用get接口驗證賬號密碼
@GetMapping("/useGetByPsw")
public Map{
return myService.useGetByPsw();
}
// 調用post接口
@PostMapping("/usePost")
public Map{
return myService.usePost();
}
}
2.2 Service
@Service
@EnableScheduling
public class MyService {
@Resource
private RestTemplate restTemplate;
String getURL = "http://localhost:8081/homepage/provideGet";
String postURL = "http://localhost:8081/homepage/providePostByMap";
public Map{
// getForObject返回值是HTTP協議的響應體
String strObject1 = restTemplate.getForObject(getURL, String.class); //無參
JSONObject jsonObject1 = JSONObject.parseObject(strObject1);
MultiValueMap
聲明:本文內容及配圖由入駐作者撰寫或者入駐合作網站授權轉載。文章觀點僅代表作者本人,不代表電子發燒友網立場。文章及其配圖僅供工程師學習之用,如有內容侵權或者其他違規問題,請聯系本站處理。
舉報投訴
-
接口
+關注
關注
33文章
8983瀏覽量
153605 -
JAVA
+關注
關注
20文章
2988瀏覽量
109102 -
代碼
+關注
關注
30文章
4896瀏覽量
70571 -
GitHub
+關注
關注
3文章
483瀏覽量
17628
發布評論請先 登錄
評論