Tuesday, September 2, 2014

How To: Download contents of a URL in Java using HTTPClient

This Java function can be used to download a webpage into a StringBuilder instance using the HTTPClient class. You have to import the necessary libraries.

public static String getURLContents(String url) {
    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet(url);
    StringBuffer str = new StringBuffer();
 
    try {
        HttpResponse response = client.execute(request);
        InputStream in = response.getEntity().getContent();
        BufferedReader reader = new BufferedReader( new InputStreamReader(in) );
        String line = "";
        while ((line = reader.readLine()) != null){
            str.append(line);
        }
        in.close();
    } catch (Exception e) {return "";}
 
    return str.toString();
}


If you have any questions, feel free to comment below.

0 comments:

Post a Comment