feign响应Image流对象

feign面向方法签名的http调用,越来越受欢迎,类型于rpc的thrift,只需要关注方法签名和返回值即可,当然feign响应流对象时,需要我们做一下特殊处理,否则会出现异常。也有一些文章通过重写HttpMessageConvert来实现,但我测试后发现还是失败的。
> Accept: image/*会返回406 Not Acceptable

### 解决方法
feign代码,注意返回值必须是`feign.Response`
```
  @PostMapping(value = "/wxa/getwxacodeunlimit")
  feign.Response getQrImagePath(@RequestParam("access_token") String accessToken,@RequestBody Map<String, Object> body);

  class WeixinClientFallback implements WeixinClient {
```
restcontroller代码,需要显示声明`produces`类型,这里因为是图片,所以声明为`MediaType.IMAGE_JPEG_VALUE`
```
 @GetMapping(value = "/v1/api/sales/qrcode", produces = MediaType.IMAGE_JPEG_VALUE)
  public void qrcode(HttpServletResponse response) {
    //获取token
    Map<String, Object> tokenMap = weixinClient.getToken("client_credential", wxAppId, wxAppSecret);
    if (tokenMap == null) {
      throw Exceptions.paramError("获取token失败");
    }
    if (tokenMap.containsKey("errcode")) {
      throw Exceptions.paramError(MapUtils.getString(tokenMap, "errmsg"));
    }
    String scene = String.format("salesPersonId=%s&agencyId=%s",
        TokenContext.getToken().getUserId(),
        TokenContext.getToken().getCompanyId());
    String token = MapUtils.getString(tokenMap, "access_token");
    Map<String, Object> requestParams = new HashMap<>();
    requestParams.put("scene", scene);
    requestParams.put("page", weixinPage);
    feign.Response imgReponse = weixinClient.getQrImagePath(token, requestParams);
    if (imgReponse == null) {
      throw Exceptions.paramError("获取二维码失败");
    }
    try (InputStream inputStream = imgReponse.body().asInputStream();
         ServletOutputStream outputStream = response.getOutputStream()) {
      response.setContentType("image/png");
      outputStream.write(IOUtils.toByteArray(inputStream));
    } catch (RuntimeException e) {
      throw Exceptions.paramError("获取二维码失败");
    } catch (Exception ex) {
      throw Exceptions.paramError("获取二维码失败");
    }
  }
```

转载于:https://www.cnblogs.com/lori/p/11305032.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值