In my Spring Boot application I have implemented the RestController
method that returns the file
in response.getOutputStream()
:
@RequestMapping(value = "/{fileId}", method = RequestMethod.GET)
@ResponseStatus(value = HttpStatus.OK)
public void getFile(@PathVariable @NotBlank String fileId, HttpServletResponse response) throws IOException, TelegramApiException {
File file = fileService.getFile(fileId);
InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
response.setContentType(FileUtils.detectMimeType(inputStream));
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, String.format("inline; filename=%s", file.getName()));
response.setContentLength((int) file.length());
FileCopyUtils.copy(inputStream, response.getOutputStream());
}
I would like to implement the integration test and use RestTemplate
in order to invoke this endpoint and receive the file.
Something like:
restTemplate.getForObject(String.format("%s/v1.0/files/%s", getBaseApiUrl(), fileId), SOMECLASS.class);
Could you please show an example how it can be properly archived with Spring RestTemplate
?
I am assuming you want to start the server and call that API to see if it really works. Using spring-test, you can do this:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class HttpRequestTest {
@LocalServerPort
private int port;
@Autowired
private TestRestTemplate restTemplate;
@Test
public void greetingShouldReturnDefaultMessage() throws Exception {
assertThat(this.restTemplate.getForObject("http://localhost:" + port + "/" + 1234, // File ID
String.class)).contains("File Content Here");
}
}
But you can actually test your logic only without start the server itself. Please refer to https://spring.io/guides/gs/testing-web/ for more info.
I have found the solution:
ResponseEntity<Resource> responseEntity = restTemplate.exchange(String.format("%s/v1.0/files/%s", getBaseApiUrl(), fileId), HttpMethod.GET, null, Resource.class);
return responseEntity.getBody().getInputStream();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.