RestTemplate

RestTemplate用于去调用远程的 REST services 时, Spring Boot 不会自动提供RestTemplate bean,但是会 auto-configure a RestTemplateBuilder, which can be used to create RestTemplate instances when needed.

e.g.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
@Service
public class RestTemplateService {
private final RestTemplate restTemplate;

RestTemplateService(RestTemplateBuilder restTemplateBuilder) {
this.restTemplate = restTemplateBuilder.build();
//添加拦截器
this.restTemplate.getInterceptors().add(new TokenInterceptor());
}
//get
public String someRestCall() {
return this.restTemplate.getForObject("http://127.0.0.1:9999/",String.class);
}
public String someJson() {
return this.restTemplate.getForObject("http://127.0.0.1:9999/bean",String.class);
}
//post
public String post() {
MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
map.add("variable","a post variable");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(map, headers);
return this.restTemplate.postForObject("http://127.0.0.1:9999/post",entity,String.class);
}
}

controller

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
@RestController
public class DemoController {
@GetMapping("/")
public String sayHello() {
return "howdy!";
}
@GetMapping("/res")
public Response res() {
return new Response();
}
@GetMapping("/v/{variable}")
public String getPathVariable(@PathVariable String variable ) {
return variable;
}
@PostMapping("/post")
public String post(Date date,String variable) {
return variable;
}
/**
* 上传文件
* @return
* @throws GeneralException
*/
@RequestMapping(
value="/upload",
method=RequestMethod.POST,
consumes= {
MediaType.APPLICATION_JSON_VALUE,
MediaType.MULTIPART_FORM_DATA_VALUE
})
public String handleFileUpload(HttpServletRequest request) throws GeneralException {
Storage storage=StorageFactory.getStorage(config.getStorageClass());
if (storage==null) {
throw new GeneralException("F105");
}
List<MultipartFile> files= ((MultipartHttpServletRequest) request).getFiles("file");
checkFileTypes(files);//检查文件类型
for(int i=0;i<files.size();++i) {
MultipartFile file=files.get(i);
if(!file.isEmpty()) {
storage.store(file);
}
}
return "success";
}
}

TestRestTemplate

测试用的RestTemplate,如果使用了@SpringBootTest,会自动配置一个TestRestTemplate,可直接使用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class DemoControllerTest {
@Autowired
private TestRestTemplate restTemplate;

@Test
public void exampleTest() {
String body = this.restTemplate.getForObject("/", String.class);
assertThat(body).isEqualTo("howdy!");
}
@Test
public void getPathVariableTest() {
String body = this.restTemplate.getForObject("/v/this is a variable", String.class);
assertThat(body).isEqualTo("this is a variable");
}
@Test
public void postTest() {
MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
map.add("date","2018-09-09");
map.add("variable","a post variable");

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(map, headers);
String body = this.restTemplate.postForObject("/post",entity,String.class);
assertThat(body).isEqualTo("a post variable");
}
@Test
public void handleFileUpload() {
String path="C:/Users/dy040/Pictures/mm.jpg";
File file=new File(path);
FileSystemResource resource =new FileSystemResource(file);
MultiValueMap<String, Object> map= new LinkedMultiValueMap<String, Object>();
map.add("file",resource);
// HttpHeaders headers = new HttpHeaders();
// headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
// HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<MultiValueMap<String, Object>>(map, headers);
String body = this.restTemplate.postForObject("/upload",map,String.class);
assertThat(body).isEqualTo("success");
}
@TestConfiguration
static class Config {

@Bean
public RestTemplateBuilder restTemplateBuilder() {
return new RestTemplateBuilder().setConnectTimeout(1000).setReadTimeout(1000);
}

}
}