如何将UriComponentsBuilder转换为java.net.URI

3
UriComponentsBuilder的文档表明将其转换为java.net.URI是可能的,但不是很直观。
下面的方法似乎可行,但需要通过toUriString()进行中间序列化。
UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(origin+base);
java.net.URI uri = null;
try {
    uri = new URI(uriBuilder.toUriString());
}
catch (Exception e) {}                                                              // TODO: insanity
String response = restTemplate.getForObject(uri,String.class);

java.net.URI的构造函数声明了一个抛出异常:java.net.URISyntaxException; 必须被捕获或声明为抛出异常。

有没有一种不需要处理异常的好方法呢?

一个真正有帮助的答案可能会提供关于为什么build有不同的返回类型取决于输入类型的见解。


uriBuilder.build 这有什么问题。 - M. Deinum
@M.Deinum:由于可能的不同返回值,它有点混乱。 - Brent Bradburn
为什么?build返回一个URI...这在你自己指向的javadoc中已经清楚地解释了...只需传入一个空映射Collections.emptyMap即可。 - M. Deinum
@M.Deinum:Collections.emptyMap()可能是我正在寻找的答案。new Object[0]似乎也可以工作。这两种方法对我来说都有点奇怪,但任何一种看起来都比我的初始解决方案好。 - Brent Bradburn
1个回答

4

新的UriComponentsBuilder类可通过提供对URI准备的所有方面(包括构建、从模板变量扩展和编码)的细粒度控制来帮助创建UriComponents实例。

{type}绑定到路径中的查询参数。

 URI uri = UriComponentsBuilder.newInstance().scheme("http").host("docuconv.claztec.net")
                .path("/cgi/{type}")
                .queryParam("path", file.getDownloadUrl())
                .queryParam("realname", file.getName())
                .queryParam("servicecode", file.getServiceCode())
                .queryParam("useragent", file.getUserAgent())
                .queryParam("charset", file.getCharset())
                .queryParam("format", file.getOption())
                .build().expand(file.getType())
                .encode()
                .toUri();

UriComponentsBuilder


这里包含了我一直在寻找的秘密配方!.build()返回类型UriComponents,它有一个函数toUri()--这就是我之前找不到的东西。 - Brent Bradburn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接