tags:

views:

78

answers:

1

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?

+4  A: 

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.

skaffman
The `set()` method is protected.
notnoop
Ah nuts. Thanks.
skaffman