S
Stefan Ram
I wonder what the best/canonical/Javaish way to get/slurp
(i.e., read the whole content into a CharSequence) a URI is.
In Perl, there is:
use LWP::Simple; $content = get( "http://example.com/" );
Say, one wanted to implement LWP::Simple::get in Java.
What is the best way to do so?
I currently do this as follows (omitting some details, like
exceptions, encodings, and close()-operations):
Connect via an HttpURLConnection object:
final java.net.URL url = new java.net.URL( uri.toString() );
final java.net.HttpURLConnection httpURLConnection
=( java.net.HttpURLConnection )url.openConnection();
httpURLConnection.connect();
Then, filling a StringBuilder from it:
final java.io.InputStreamReader inputStreamReader
= new java.io.InputStreamReader
( httpURLConnection.getInputStream(), "UTF-8" );
final java.io.BufferedReader bufferedReader
= new java.io.BufferedReader( inputStreamReader );
java.lang.String line; while(( line = bufferedReader.readLine() )!= null )
{ stringBuilder.append( line ); stringBuilder.append( '\n' ); }
Is this the best/usual/canonical/Javaish way to do it,
or should I use anything else?
(i.e., read the whole content into a CharSequence) a URI is.
In Perl, there is:
use LWP::Simple; $content = get( "http://example.com/" );
Say, one wanted to implement LWP::Simple::get in Java.
What is the best way to do so?
I currently do this as follows (omitting some details, like
exceptions, encodings, and close()-operations):
Connect via an HttpURLConnection object:
final java.net.URL url = new java.net.URL( uri.toString() );
final java.net.HttpURLConnection httpURLConnection
=( java.net.HttpURLConnection )url.openConnection();
httpURLConnection.connect();
Then, filling a StringBuilder from it:
final java.io.InputStreamReader inputStreamReader
= new java.io.InputStreamReader
( httpURLConnection.getInputStream(), "UTF-8" );
final java.io.BufferedReader bufferedReader
= new java.io.BufferedReader( inputStreamReader );
java.lang.String line; while(( line = bufferedReader.readLine() )!= null )
{ stringBuilder.append( line ); stringBuilder.append( '\n' ); }
Is this the best/usual/canonical/Javaish way to do it,
or should I use anything else?