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("獲取二維碼失敗");
}
}
```api