Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a android.net.Uri from a java.net.URL?

Tags:

java

android

I would like to use intent.setData(Uri uri) to pass data obtained from a URL. In order to do this, I need to be able to create a Uri from a URL (or from a byte[] I read from the URL, or a ByteArrayInputStream I create from the byte[], etc). However, I cannot figure out how this is supposed to be done.

So, is there anyway to create a Uri from data obtained from a URL without first writing the data to a local file?

like image 668
ab11 Avatar asked Nov 23 '11 09:11

ab11


People also ask

What is Java URI Android?

A URI is a uniform resource identifier while a URL is a uniform resource locator.

What is Java Net URI?

What is URI? URI stands for Uniform Resource Identifier. A Uniform Resource Identifier is a sequence of characters used for identification of a particular resource. It enables for the interaction of the representation of the resource over the network using specific protocols.


2 Answers

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

Example:

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

Make sure to handle relevant exception, such as URISyntaxException.

like image 129
Buhake Sindi Avatar answered Sep 29 '22 18:09

Buhake Sindi


I think your answer can be found from here..

Uri.Builder.build() works quite well with normal URLs, but it fails with port number support.

The easiest way that I discovered to make it support port numbers was to make it parse a given URL first 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

like image 29
Shalin Avatar answered Sep 29 '22 18:09

Shalin