Sam Sam - 1 year ago 276
Java Question

How to programmatically consume a file from a Rest API using Spring?

I have the following Rest resource which downloads a file from DB. It works fine from the browser, however, when I try to do it from a Java client as below, I get 406 (Not accepted error).

@RequestMapping(value="/download/{name}", method=RequestMethod.GET,
public @ResponseBody HttpEntity<byte[]> downloadActivityJar(@PathVariable String name) throws IOException
{"downloading : " + name + " ... ");
byte[] file = IOUtils.toByteArray(artifactRepository.downloadJar(name));
HttpHeaders header = new HttpHeaders();
header.set("Content-Disposition", "attachment; filename="+ name + ".jar");

return new HttpEntity<byte[]>(file, header);

The client is deployed on the same server with different port (message gives the correct name) :

RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:8080/activities/download/" + message.getActivity().getName();
File jar = restTemplate.getForObject(url, File.class);"File size: " + jar.length() + " Name: " + jar.getName());

What am I missing here?

Answer Source

The response code is 406 Not Accepted. You need to specify an 'Accept' request header which must match the 'produces' field of your RequestMapping.

RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new ByteArrayHttpMessageConverter());    
HttpHeaders headers = new HttpHeaders();
HttpEntity<String> entity = new HttpEntity<String>(headers);

ResponseEntity<byte[]> response =, HttpMethod.GET, entity, byte[].class, "1");

                FileOutputStream output = new FileOutputStream(new File("filename.jar"));
                IOUtils.write(response.getBody(), output);