1、UriComponents
1.1、构建请求地址
UriComponentsBuilder 可以帮助你通过URI模板以及变量构建URI地址,并且可以根据选择的构建方法fromHttpUrl或fromUriString或其他方法对模板内容进行正则表达式检测。

样例如下:
String access_token = "gvs_6u1SW4ck+ku,lbm";
//String id = "1000005";
String id = null;
String string = UriComponentsBuilder.fromHttpUrl("https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token={ACCESS_TOKEN}&id={ID}").encode(StandardCharsets.UTF_8).build(access_token, id).toString();
System.out.println(string);
输出结果:
https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=gvs_6u1SW4ck%2Bku%2Clbm&id=1000005
或
https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=gvs_6u1SW4ck%2Bku%2Clbm&id=
上例中我们的URI模板中的变量通过{ACCESS_TOKEN}和{ID}进行占位,后续通过build方法传递对应数量的值即可按顺序替换,传递的值可为null。
如果希望替换时根据变量名称替换,则可传递一个map对象,map的key为占位符中的名称,如ACCESS_TOKEN和ID,此时不带{},value则为你需要替换的真实的值。value的值也可为null,输出同上。
样例如下:
String access_token = "gvs_6u1SW4ck+ku,lbm";
String id = "1000005";
//String id = null;
Map<String, Object> uriVariables = new HashMap<>();
uriVariables.put("ACCESS_TOKEN", access_token);
uriVariables.put("ID", id);
String string = UriComponentsBuilder.fromHttpUrl("https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token={ACCESS_TOKEN}&id={ID}").encode(StandardCharsets.UTF_8).build(uriVariables).toString();
System.out.println(string);
更多使用方法方式可自行体验测试!
1.2、HttpServletRequest请求解析
当我们有做操作日志或是接口日志拦截记录需求时,一般需要获取请求的地址以及请求的参数信息,此时我们就可以通过ServletUriComponentsBuilder.fromRequest(request).build()快速构建一个UriComponents对象,然后直接调用它的相关方法获取所需的信息即可。
样例如下:
UriComponents uriComponents = ServletUriComponentsBuilder.fromRequest(request).build();
System.out.println(uriComponents.getPath());
System.out.println(uriComponents.getQuery());
输出如:
/coupons/couponSeries/page
spm=03060bb423c0414fac9f796d1d7152a9&page=1&pageSize=10
更多使用方法方式可自行体验测试!
2020-12-08 20:50
阅读原文