I have a java.net.URL object that uses the HTTPS protocol, e.g.:
https://www.bla.com
And I have to change only the protocol part of this URL object so that when I call it's toString() method I get this:
http://www.bla.com
What is the best way to do that?
In your Java program, you can use a String containing this text to create a URL object: URL myURL = new URL("http://example.com/"); The URL object created above represents an absolute URL. An absolute URL contains all of the information necessary to reach the resource in question.
openConnection. Returns a URLConnection instance that represents a connection to the remote object referred to by the URL . A new instance of URLConnection is created every time when invoking the URLStreamHandler. openConnection(URL) method of the protocol handler for this URL.
The getPath() function is a part of URL class. The function getPath() returns the Path name of a specified URL.
You'll have the use the methods available to you:
URL oldUrl = new URL("https://www.bla.com");
URL newUrl = new URL("http", oldUrl.getHost(), oldUrl.getPort(), oldUrl.getFile(), oldUrl.getRef());
There's an even more expansive set() method that takes 8 items, you might need that for more elaborate URLs.
Edit: As was just pointed out to me, I wasn't paying attention, and set() is protected. So URL is technically mutable, but to us mortals, it's immutable. So you'll just have to construct a new URL object.
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