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("获取二维码失败");
}
}
```
上一篇: BZOJ1008