I am trying to establish a communication between two micros, where the first one receives a petition from the frontend and contacts with another micro, which creates an excel file and sends it back to the first micro, starting the download of the file.
First, I tried to print a simple String response to check the communication between micros and that worked correctly, but the same thing for files didn't work.
Here is the code that I am following: For Controller A:
@GetMapping(path="/test")
public void getEntities2(HttpServletRequest request, HttpServletResponse response) throws IOException {
ResponseEntity<Workbook> responseEntity = new RestTemplate()
.getForEntity("http://localhost:8080/proceso/excel", Workbook.class);
assertThat(responseEntity.getStatusCode(), equalTo(HttpStatus.OK));
response.setHeader("Content-disposition", "attachment; filename=" + "test.xls");
Workbook workbook = responseEntity.getBody();
workbook.write(response.getOutputStream());
workbook.close();
}
The second Controller (Excel file generator):
@GetMapping(path="/excel")
public ResponseEntity<Workbook> test3(HttpServletResponse response) throws Exception {
HashMap<String, ArrayList<String>> test = new HashMap<String, ArrayList<String>>();
Workbook workbook = CreateExcel.excelCreator(test);
Workbook responseFile = workbook;
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + "test.xls")
.contentType(MediaType.MULTIPART_FORM_DATA)
.body(responseFile);
}
And then the following error appears:
org.springframework.web.client.HttpClientErrorException$NotAcceptable: 406 null
I just want to receive the file in the first controller and download the Excel from localhost. Is there any way to do it? Thanks all.
I discovered the problem. The excel file is a octet-stream file so it needs to be received as a byte[] array. This is the Controller A:
@GetMapping(path="/")
public ResponseEntity<byte[]> getEntities() throws IOException {
ResponseEntity<byte[]> responseEntity = new RestTemplate()
.getForEntity("http://localhost:8080/excel", byte[].class);
assertThat(responseEntity.getStatusCode(), equalTo(HttpStatus.OK));
return responseEntity;
}
And Controller B:
@GetMapping(path="/excel")
public void getExcel(HttpServletResponse response) throws Exception {
Iterable<InstancesAggregate> list = instancesAggregate.myfindAll(); //Creating a list
HashMap<String, ArrayList<String>> test = CreateExcel.setExcelProceso(list);
Workbook workbook = CreateExcel.excelCreator(test);
response.setHeader("Content-disposition", "attachment; filename=" + "test.xls");
workbook.write(response.getOutputStream());
workbook.close();
}
This works fine for me, hope someone find the info useful.