17

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?

Line
  • 1,397
  • 3
  • 14
  • 39
MTilsted
  • 5,038
  • 9
  • 40
  • 71
  • Why don't you want to use the URL class? – Andy May 18 '12 at 19:29
  • 1
    The problem with URL is that equals and hashcode are blocking operations which does network lookup. Url also seems to be missing a method to normalize a url and convert an relative url to an absolute url. – MTilsted May 19 '12 at 04:40
  • ["Use `URI` where possible" – Java Puzzlers Episode VI](https://youtu.be/wDN_EYUvUq0?t=9m58s). – MC Emperor Aug 20 '18 at 13:12

5 Answers5

15

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();
}
azro
  • 47,041
  • 7
  • 30
  • 65
Vijay Shanker Dubey
  • 4,170
  • 6
  • 28
  • 48
6

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

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

Jeffrey
  • 43,506
  • 7
  • 88
  • 140
5

You should use ContentResolver to obtain InputStream:

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

Code is valid inside Activity object scope.

marioc64
  • 381
  • 3
  • 11
3

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

Hkachhia
  • 4,275
  • 5
  • 38
  • 74
ControlAltDel
  • 32,042
  • 9
  • 48
  • 75
0

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

premnathcs
  • 535
  • 3
  • 11