2015-02-23 25 views
1

我有下面的控制器與一個產生xml MediaType的RequestMapping。從彈簧控制器中產生xml的異常MediaType

@RestController 
    @RequestMapping("/api") 
    public class ArticleResource { 

    @RequestMapping(value = "/xml/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_XML_VALUE) 
     public ResponseEntity<byte[]> getXml(@PathVariable(value = "id") String id, 
               final HttpServletRequest request, 
               final HttpServletResponse response) { 
      InputStream inputStream = null; 
      try { 
       inputStream = new FileInputStream(path + id + ".xml"); 

      } catch (FileNotFoundException e) { 
       throw new BadRequestException("No such xml exists"); 
      } 
      try { 
       return new ResponseEntity<byte[]>(IOUtils.toByteArray(inputStream), HttpStatus.OK); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
      return new ResponseEntity<byte[]>(HttpStatus.NOT_FOUND); 
     } 
    } 

的BadRequestException實現如下:

它當XML存在工作正常,但是當XML無法找到我有一個406錯誤代碼。我想這個問題發生是因爲它期望一個xml媒體類型,而是返回一個RuntimeException。我該如何解決這個問題?

回答

0

您的HTTP請求中是否有Accept:標頭?如果客戶端需要XML,您的錯誤處理程序將只返回HTTP錯誤代碼(響應狀態),因此它會在客戶端導致406 Not Acceptable。 如果是這種情況,您可以從錯誤處理程序返回一個XML響應實體並更新您的簽名以反映它生成XML。或者您可以嘗試從您的請求中刪除Accepts

0

我解決我的問題,通過返回如下:

String returnString = "XML file don't exists"; 
return new ResponseEntity<byte[]>(IOUtils.toByteArray(
         new ByteArrayInputStream(returnString.getBytes())), HttpStatus.NOT_FOUND);