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

标签 java spring uri

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; must be caught or declared to be thrown

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

一个真正有用的答案可能会提供一些见解,说明为什么 build 根据输入类型具有不同的返回类型。

最佳答案

A new UriComponentsBuilder class helps to create UriComponents instances by providing fine-grained control over all aspects of preparing a URI including construction, expansion from template variables, and encoding.

{type} 绑定(bind)到路径中的 queryParam。

 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

关于java - 如何将 UriComponentsBuilder 转换为 java.net.URI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49664787/

相关文章:

java - 将 ConstraintValidator 实现注册到 Constraint

android - Uri.builder 与基于字符串的 url 构造

java - Android 的新 Google Play 游戏服务排行榜 API

java - 无法提交 JPA 事务 - RollbackException : Transaction marked as rollbackOnly

java - Spring 应用程序抛出 ArrayIndexOutOfBoundsException

ruby-on-rails - 在 Ruby 中解析复杂的 URL

cocoa - 来自临时 URI 的永久 NSManagedObject URI?

Java:为什么我需要初始化一个原始局部变量?

java - Android mpandroidchart 带截止点的折线图

java - WebSockets 请求中请求的资源上不存在 'Access-Control-Allow-Origin' header