前言:

我们在与第三方接口通信的时候,经常需要http调用。不管是httpclient,okhttp,resttemplate再到更牛一些的http客户端。

地址构建与参数拼接是我们逃脱不掉的。

推荐使用 UriComponentsBuilder,包路径为:org.springframework.web.util,这个类的方法有许多,主要围绕如何构建url和传递参数来的。用来解决我们在日常生活中参数拼接的痛苦(或者拼多了,或者拼少了,或者拼错了)。

【开发心得】使用UriComponentsBuilder/UriComponents构建请求url_传递参数

常规的例子:

UriComponents uriComponents=UriComponentsBuilder
        .fromHttpUrl("http://localhost:8080//test")
        .queryParams(params).build() //params是个Map
String uri=uriComponents.toUriString();

模板方式构建:
expand(): 替换参数。
encode(): 编码,默认使用utf-8。

UriComponents uriComponents = UriComponentsBuilder
.fromUriString("http://example.com/hotels/{hotel}/bookings/{booking}").build();
URI uri = uriComponents.expand("42", "21").encode().toUri();

注意:UriComponents是不可变的,expand()和encode()返回新的实例。
上述例子也可以这样实现:

UriComponents uriComponents = UriComponentsBuilder.newInstance()
  .scheme("http").host("example.com").path("/hotels/{hotel}/bookings/{booking}").build()
  .expand("42", "21")
  .encode();

要注意的是expand是一个可变数组的传参,并且要与前边模板写法的参数一一对应。