Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert UriComponentsBuilder to java.net.URI

Tags:

java

uri

spring

The documentation for UriComponentsBuilder suggest that it is possible, but not straightforward to convert to a java.net.URI.

The following seems to work, but involves an intermediate serialization by 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);

The constructor for java.net.URI declares a throw:

java.net.URISyntaxException; must be caught or declared to be thrown

Is there a nice way of doing this that doesn't require dealing with exceptions?

A really helpful answer might provide some insight as to why build has different return types depending on the input type.

like image 489
Brent Bradburn Avatar asked Jan 22 '26 04:01

Brent Bradburn


1 Answers

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.

The {type} bind to queryParam in path.

 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

like image 126
0gam Avatar answered Jan 23 '26 19:01

0gam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!