In java, I'd like to replace the Host
part of an url with a new Host
, where both the host and url are supplied as a string.
This should take into account the fact that the host could have a port in it, as defined in the RFC
Does anyone know of any libraries or routines that do Host
replacement in an url correctly?
EDIT: For my use case, I want my host replacement to match what a java servlet would respond with. I tried this out by running a local java web server, and then tested it using curl -H 'Host:superduper.com:80' 'http://localhost:8000/testurl'
and having that endpoint simply return the url from request.getRequestURL().toString()
, where request is a HttpServletRequest
. It returned http://superduper.com/testurl
, so it removed the default port for http, so that's what I'm striving for as well.
getHost() function is a part of URL class. The function getHost() returns the Host of a specified URL. The Host part of the URL is the host name of the URL. The format of the host conforms to RFC 2732.
Using String.replace() is used to replace all occurrences of a specific character or substring in a given String object without using regex. There are two overloaded methods available in Java for replace() : String. replace() with Character, and String. replace() with CharSequence.
The getHost() method of URL class returns the hostname of the URL. This method will return the IPv6 address enclosed in square brackets ('['and']').
The Spring Framework provides the UriComponentsBuilder
. You can use it like this:
import org.springframework.web.util.UriComponentsBuilder;
String initialUri = "http://localhost/me/out?it=5";
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(initialUri);
String modifiedUri = builder.host("myserver").port("20000").toUriString();
System.out.println(modifiedUri);
// ==> http://myserver:20000/me/out?it=5
Here you need to provide hostname and port in separate calls to get right encoding.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With