Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open stream from uri

Tags:

java

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?

like image 843
MTilsted Avatar asked May 18 '12 18:05

MTilsted


3 Answers

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();
}
like image 51
Vijay Shanker Dubey Avatar answered Oct 06 '22 20:10

Vijay Shanker Dubey


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

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

like image 34
Jeffrey Avatar answered Oct 06 '22 20:10

Jeffrey


You should use ContentResolver to obtain InputStream:

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

Code is valid inside Activity object scope.

like image 45
marioc64 Avatar answered Oct 06 '22 18:10

marioc64