title: How to return an image in Spring Boot controller and serve like a file system
body: <p>I've tried the various ways given in Stackoverflow, maybe I missed something.</p>
  
  <p>I have an Android client (whose code I can't change) which is currently getting an image like this:</p>
  
  <pre><code>HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setRequestMethod("GET");
  connection.connect();
  </code></pre>
  
  <p>Where <code>url</code> is the location of the image (static resource on CDN). Now my Spring Boot API endpoint needs to behave like a file resource in the same way so that the same code can get images from the API (Spring boot version 1.3.3).</p>
  
  <p>So I have this:</p>
  
  <pre><code>@ResponseBody
  @RequestMapping(value = "/Image/{id:.+}", method = RequestMethod.GET, consumes = MediaType.ALL_VALUE, produces = MediaType.IMAGE_JPEG_VALUE)
  public ResponseEntity&lt;byte[]&gt; getImage(@PathVariable("id")String id) {
      byte[] image = imageService.getImage(id);  //this just gets the data from a database
      return ResponseEntity.ok(image);
  }
  </code></pre>
  
  <p>Now when the Android code tries to get <code>http://someurl/image1.jpg</code> I get this error in my logs:</p>
  
  <blockquote>
    <p>Resolving exception from handler [public
    org.springframework.http.ResponseEntity
    com.myproject.MyController.getImage(java.lang.String)]:
    org.springframework.web.HttpMediaTypeNotAcceptableException: Could not
    find acceptable representation</p>
  </blockquote>
  
  <p>Same error happens when I plug <code>http://someurl/image1.jpg</code> into a browser.</p>
  
  <p>Oddly enough my tests check out ok:</p>
  
  <pre><code>Response response = given()
              .pathParam("id", "image1.jpg")
              .when()
              .get("MyController/Image/{id}");
  
  assertEquals(HttpStatus.OK.value(), response.getStatusCode());
  byte[] array = response.asByteArray(); //byte array is identical to test image
  </code></pre>
  
  <p>How do I get this to behave like an image being served up in the normal way? (Note I can't change the content-type header that the android code is sending)</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>Code after comments (set content type, take out <code>produces</code>):</p>
  
  <pre><code>@RequestMapping(value = "/Image/{id:.+}", method = RequestMethod.GET, consumes = MediaType.ALL_VALUE)
  public ResponseEntity&lt;byte[]&gt; getImage(@PathVariable("id")String id, HttpServletResponse response) {
      byte[] image = imageService.getImage(id);  //this just gets the data from a database
      response.setContentType(MediaType.IMAGE_JPEG_VALUE);
      return ResponseEntity.ok(image);
  }
  </code></pre>
  
  <p>In a browser this just seems to give a stringified junk (byte to chars i guess). In Android it doesn't error, but the image doesn't show.</p>