http - Read url to string in few lines of java code -
i'm trying find java's equivalent groovy's:
string content = "http://www.google.com".tourl().gettext();
i want read content url string. don't want pollute code buffered streams , loops such simple task. looked apache's httpclient don't see 1 or 2 line implementation.
this answer refers older version of java. may want @ ccleve's answer below.
here traditional way this:
import java.net.*; import java.io.*; public class urlconnectionreader { public static string gettext(string url) throws exception { url website = new url(url); urlconnection connection = website.openconnection(); bufferedreader in = new bufferedreader( new inputstreamreader( connection.getinputstream())); stringbuilder response = new stringbuilder(); string inputline; while ((inputline = in.readline()) != null) response.append(inputline); in.close(); return response.tostring(); } public static void main(string[] args) throws exception { string content = urlconnectionreader.gettext(args[0]); system.out.println(content); } }
as @extraneon has suggested, ioutils allows in eloquent way that's still in java spirit:
inputstream in = new url( "http://jakarta.apache.org" ).openstream(); try { system.out.println( ioutils.tostring( in ) ); } { ioutils.closequietly(in); }
Comments
Post a Comment