18

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,529
  • 3
  • 18
  • 42
MTilsted
  • 5,425
  • 9
  • 44
  • 76
  • 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

16

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
  • 53,056
  • 7
  • 34
  • 70
Vijay Shanker Dubey
  • 4,308
  • 6
  • 32
  • 49
6

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

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

Jeffrey
  • 44,417
  • 8
  • 90
  • 141
5

You should use ContentResolver to obtain InputStream:

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

Code is valid inside Activity object scope.

marioc64
  • 381
  • 3
  • 12
3

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

Hkachhia
  • 4,463
  • 6
  • 41
  • 76
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
0

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

premnathcs
  • 545
  • 3
  • 11