系统使用微服务架构,所以调用第三方接口使用RestTemplate,在报文实体和Java对象之间还需要进行转换,SpringMVC和RestTemplate提供了HttpMessageConverter作为转换器,具体流程如下图
![](https://img.haomeiwen.com/i7584463/19f8f6a532dc2142.png)
HttpMessageConverter的介绍SpringMVC - HttpMessageConverter与返回JSON - 小小默:进无止境 - CSDN博客服务器返回的可能有多种类型(application/json, application/atom+xml, application/x-www-form-urlencoded, application/octet-stream, application/pdf, application/rss+xml, application/xhtml+xml, application/xml, text/event-stream, text/html, text/markdown, text/plain, text/xml, application/*+json, image/vnd.wap.wbmp, image/png, image/x-png, image/jpeg, image/bmp, image/gif),所以转换器接口HttpMessageConverter会有多个接口将报文实体和java对象进行转换
![](https://img.haomeiwen.com/i7584463/b0419ba0a842cb2d.png)
调用微信应用接口接口大概的流程
1、获取接口调用凭证
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={secret}
如果调用成功返回 {"access_token ":"fsfnesf5f88sfs558w1212fsf5524fs22fs","expires_in","7200"}
access_token 接口调用凭证
expires_in 凭证有效时间,单位:秒。目前是7200秒之内的值
将返回的结果用封装的对象接受
![](https://img.haomeiwen.com/i7584463/7c143f57a77e34af.png)
![](https://img.haomeiwen.com/i7584463/62b9b4a525b04397.png)
这里使用了FastJSON格式化属性,但RestTemplate默认使用Jackson,提供了MappingJackson2HttpMessageConverter转换器
![](https://img.haomeiwen.com/i7584463/630af733689163c6.png)
![](https://img.haomeiwen.com/i7584463/79d4f2766223bebb.png)
FastJson的注解不起作用,现在改用FastJson转换器
![](https://img.haomeiwen.com/i7584463/0d552f7e9276a562.png)
由图(1)可看出RestTemplate支持的转换器释放到数组中,图(2)可看出如果找到能处理Content-Tyep类型的转换器并且Java实体类和Content-Tyep也对应就会执行read()方法并返回,队列中剩下的转换器不会再查找,所以用FastJson转换器替换JackJson转换器的思路就是把:FastJson转换器放在数组的第一个元素,这个这个执行,jsckJson转换器就不会再执行
![](https://img.haomeiwen.com/i7584463/ee0b3609f7fdbded.png)
![](https://img.haomeiwen.com/i7584463/895c0f06438db560.png)
![](https://img.haomeiwen.com/i7584463/46626beb7b25b043.png)
2、微信接口的调用可以参考微信接口文档getWXACodeUnlimit · 小程序
调用接口报错
![](https://img.haomeiwen.com/i7584463/b49c078678358a9e.png)
![](https://img.haomeiwen.com/i7584463/822bc6e8beb4f227.png)
![](https://img.haomeiwen.com/i7584463/42642e3be7360ec0.png)
RestTmplate默认没有支持image/jpge的转换器,查找资料
![](https://img.haomeiwen.com/i7584463/c9ca239ded774560.png)
如果直接将BufferedimagehttpMessageConverter添加到RestTemplate支持的转换器中也不会起作用,只有是GenericHttpMessageConverter接口的实现类才符合要求
![](https://img.haomeiwen.com/i7584463/dcb99d40130319f0.png)
![](https://img.haomeiwen.com/i7584463/39153ee75140c286.png)
现在的解决的方法是(可能还有更优雅的方法),自定义一个转换器MyHttpMessageConverter实现GenericHttpMessageConverter接口,在将BufferedimagehttpMessageConverter实现方法复制过来
![](https://img.haomeiwen.com/i7584463/9d288f4975f31ef4.png)
![](https://img.haomeiwen.com/i7584463/9a4fac9018d32381.png)
image/pg使用BufferedImage对象接受
![](https://img.haomeiwen.com/i7584463/1f64dea8cb8e7fff.png)
执行成功了
![](https://img.haomeiwen.com/i7584463/85cda0007591af31.png)
网友评论