Convert String to Uri

Viewed 353605

How can I convert a String to a Uri in Java (Android)? i.e.:

String myUrl = "http://stackoverflow.com";

myUri = ???;

8 Answers

Java's parser in java.net.URI is going to fail if the URI isn't fully encoded to its standards. For example, try to parse: http://www.google.com/search?q=cat|dog. An exception will be thrown for the vertical bar.

urllib makes it easy to convert a string to a java.net.URI. It will pre-process and escape the URL.

assertEquals("http://www.google.com/search?q=cat%7Cdog",
    Urls.createURI("http://www.google.com/search?q=cat|dog").toString());
import java.net.URI;

Below also works for me :

URI uri = URI.create("http://stackoverflow.com");

OR

URI uri = new URI("http://stackoverflow.com");

you can do this too

for http

var response = await http.get(Uri.http("192.168.100.91", "/api/fetch.php"));

or

for https

var response = await http.get(Uri.https("192.168.100.91", "/api/fetch.php"));
Related