MTilsted
MTilsted

Reputation: 5543

Open stream from uri

I got an uri (java.net.URI) such as http://www.example.com. How do I open it as a stream in Java?

Do I really have to use the URL class instead?

Upvotes: 20

Views: 32388

Answers (5)

marioc64
marioc64

Reputation: 390

You should use ContentResolver to obtain InputStream:

InputStream is = getContentResolver().openInputStream(uri);

Code is valid inside Activity object scope.

Upvotes: 6

Vijay Shanker Dubey
Vijay Shanker Dubey

Reputation: 4418

You will have to create a new URL object and then open stream on the URL instance. An example is below.

try {

   URL url = uri.toURL(); //get URL from your uri object
   InputStream stream = url.openStream();

} catch (MalformedURLException e) {
   e.printStackTrace();
} catch (URISyntaxException e) {
   e.printStackTrace();
}catch (IOException e) {
   e.printStackTrace();
}

Upvotes: 18

ControlAltDel
ControlAltDel

Reputation: 35096

uri.toURL().openStream() or uri.toURL().openConnection().getInputStream()

Upvotes: 3

Jeffrey
Jeffrey

Reputation: 44808

URLConnection connection = uri.toURL().openConnection()

Yes, you have to use the URL class in one way or the other.

Upvotes: 6

premnathcs
premnathcs

Reputation: 555

You can use URLConnection to read data for given URL. - URLConnection

Upvotes: 0

Related Questions