Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change only the protocol part of a java.net.URL object?

Tags:

java

http

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?

like image 681
Alceu Costa Avatar asked Jul 23 '09 12:07

Alceu Costa


People also ask

How do I create an HTTP URL in Java?

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.

What does URL openConnection do?

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.

How do I find the path of a URL?

The getPath() function is a part of URL class. The function getPath() returns the Path name of a specified URL.


1 Answers

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.

like image 90
skaffman Avatar answered Sep 20 '22 14:09

skaffman