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

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -