How to create a URI from a URL?

I would like to use intent.setData(URI) to pass data retrieved from the URL. To do this, I need to create a URI from the URL (or from the bytes [] that I read from the URL, or ByteArrayInputStream , which I create from byte[] , etc.). However, I cannot understand how this should be done.

So, is there anyway the creation of a URI from the data obtained from the URL without first writing the data to the local file?

+24
java android
Nov 23 '11 at 9:51
source share
7 answers

Use the URL.toURI() ( Android doc ) method.

Example:

 URL url = new URL("http://www.google.com"); //Some instantiated URL object URI uri = url.toURI(); 

Be sure to handle the appropriate exception, such as a URISyntaxException .

+39
Nov 23 '11 at 9:57
source share

I think your answer can be found here ..

Uri.Builder.build() works pretty well with regular URLs, but it fails to support the port number.

The easiest way I found to support port numbers was to parse the given URL first and then work with it.

 Uri.Builder b = Uri.parse("http://www.yoursite.com:12345").buildUpon(); b.path("/path/to/something/"); b.appendQueryParameter("arg1", String.valueOf(42)); if (username != "") { b.appendQueryParameter("username", username); } String url = b.build().toString(); 

Source: http://twigstechtips.blogspot.com/2011/01/android-create-url-using.html

+9
Nov 23 2018-11-11T00:
source share

Note that on Android, Uris are different from Java URIs. Here's how to avoid using hardcoded strings and at the same time create a Uri with only part of the string path of the http URL encoded in accordance with RFC2396:

Example URL string:

 String thisUrl = "http://lapi.transitchicago.com/api/1.0/ttarrivals.aspx?key=[redacted]&mapid=value" 

method:

 private Uri.Builder builder; public Uri getUriFromUrl(String thisUrl) { URL url = new URL(thisUrl); builder = new Uri.Builder() .scheme(url.getProtocol()) .authority(url.getAuthority()) .appendPath(url.getPath()); return builder.build(); } 

To handle query strings, you need to parse url.getQuery () as described here , and then pass this to the constructor. appendQueryParameter ().

+3
Feb 27 '14 at 5:17
source share
 try { uri = new URI(url.toString()); } catch (URISyntaxException e) { } 
+2
Nov 23 '11 at 9:59
source share

From How to create a Uri from a URL?

 Uri uri = Uri.parse( "http://www.facebook.com" ); 
+1
Apr 15 '16 at 18:30
source share
 URI uri = null; URL url = null; // Create a URI try { uri = new URI("www.abc.com"); } catch (URISyntaxException e) { } // Convert an absolute URI to a URL try { url = uri.toURL(); } catch (IllegalArgumentException e) { // URI was not absolute } catch (MalformedURLException e) { } // Convert a URL to a URI try { uri = new URI(url.toString()); } catch (URISyntaxException e) { } 
0
Nov 23 '11 at 10:18
source share

We can parse any uri from uri with

 Uri uri = Uri.parse( "http://www.google.com" ); 
0
Sep 04 '17 at 9:50
source share



All Articles