no suitable HttpMessageConverter found for response type [class java.io.InputStream]

你的名字 2024-03-31 16:26 201阅读 0赞

报错

使用springrestful 获取流的时候,报错

  1. @Autowired
  2. private RestTemplate restTemplate;
  3. restTemplate.getForObject(url, InputStream.class);

请求报错:

  1. Could not extract response: no suitable HttpMessageConverter found for response type [class java.io.InputStream] and content type [application/force-download]

方法1: 推荐使用

使用 org.springframework.core.io.Resource.class 来接收

  1. org.springframework.core.io.Resource forObject = restTemplate.getForObject(url, org.springframework.core.io.Resource.class);
  2. InputStream inputStream = Objects.requireNonNull(forObject).getInputStream();

方法2:

直接用httpclient 请求,可以直接获取到流:

  1. public static InputStream sendGet(String url) {
  2. InputStream inputStream = null;
  3. try {
  4. // 创建URL对象
  5. URL connURL = new URL(url);
  6. // 打开URL连接
  7. java.net.HttpURLConnection httpConn = (java.net.HttpURLConnection) connURL.openConnection();
  8. // 设置通用属性
  9. httpConn.setRequestProperty("Accept", "*/*");
  10. httpConn.setRequestProperty("Connection", "Keep-Alive");
  11. httpConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
  12. // 建立实际的连接
  13. httpConn.connect();
  14. inputStream = httpConn.getInputStream();
  15. } catch (Exception e) {
  16. e.printStackTrace();
  17. }
  18. return inputStream;
  19. }

发表评论

表情:
评论列表 (有 0 条评论,201人围观)

还没有评论,来说两句吧...

相关阅读