前言
SpringBoot项目发送Get或Post请求
以微信小程序后端获取openid为例
引入包
1
| import org.springframework.web.client.RestTemplate;
|
定义一个实体类
- 定义一个用于处理接收响应的实体类
- 如果不定义,可以使用Map或Object类接收响应
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| public class WxToken {
private String openid; private String session_key; private String unionid; private String errcode; private String errmsg;
public WxToken(String openid, String session_key, String unionid, String errcode, String errmsg) { this.openid = openid; this.session_key = session_key; this.unionid = unionid; this.errcode = errcode; this.errmsg = errmsg; }
}
|
发送请求并处理响应
没有参数
WxToken.class
:指定接受响应的类,如果没有定义实体类,可以使用Object.class
或者Map.class
1 2 3 4 5 6
| String url = "https://api.weixin.qq.com/sns/jscode2session";
RestTemplate restTemplate = new RestTemplate(); WxToken wxToken = restTemplate.getForObject(url, WxToken.class);
|
地址后面传递参数
1 2 3 4 5 6 7 8 9 10 11 12
| String js_code = ""; String appid = ""; String secret = ""; String grant_type = "authorization_code";
String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+secret+"&grant_type="+grant_type+"&js_code="+js_code;
RestTemplate restTemplate = new RestTemplate(); WxToken wxToken = restTemplate.getForObject(url, WxToken.class);
|
通过Map传递参数
1 2 3 4 5 6 7 8 9 10 11 12 13
| Map<String, Object> map = new HashMap(); map.put("js_code", ""); map.put("appid", ""); map.put("secret", ""); map.put("grant_type", "authorization_code");
String url = "https://api.weixin.qq.com/sns/jscode2session";
RestTemplate restTemplate = new RestTemplate(); WxToken wxToken = restTemplate.getForObject(url, WxToken.class, map);
|
通过自定义对象传递参数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| public class Paramter {
private String js_code; private String appid; private String secret; private String grant_type;
public Paramter(String js_code, String appid, String secret, String grant_type) { this.js_code = js_code; this.appid = appid; this.secret = secret; this.grant_type = grant_type; }
}
|
1 2 3 4 5 6 7 8 9
| Paramter paramter = new Paramter("", "", "", "authorization_code");
String url = "https://api.weixin.qq.com/sns/jscode2session";
RestTemplate restTemplate = new RestTemplate(); WxToken wxToken = restTemplate.getForObject(url, WxToken.class, paramter);
|
踩坑
- 获取微信小程序的openid时,虽然官方说明文档说传递回来的是json数据,但事实上是text的数据,而RestTemplate在处理响应时,只能处理json数据,所以需要把text的数据转换为json的数据才可以让RestTemplate处理响应
解决问题
- 创建一个转换数据格式的类,继承自MappingJackson2HttpMessageConverter类
1 2 3 4 5 6 7 8 9 10
| class WxMappingJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter {
public WxMappingJackson2HttpMessageConverter(){ List<MediaType> mediaTypes = new ArrayList<>(); mediaTypes.add(MediaType.TEXT_PLAIN); mediaTypes.add(MediaType.TEXT_HTML); setSupportedMediaTypes(mediaTypes); }
}
|
- 在发送请求前,为RestTemplate指定处理响应数据的方式
1 2 3 4 5
| restTemplate.getMessageConverters().add(new WxMappingJackson2HttpMessageConverter());
WxToken wxToken = restTemplate.getForObject(url, WxToken.class);
|
完成
参考文献
CSDN——kinginblue