simPod
simPod

Reputation: 13506

How to get webpage HTML

I'm trying to load a webpage html in my Android app with the following code:

    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet("http://www.stackoverflow.com/");
    HttpResponse response = client.execute(request);

    String html = "";

    InputStream in = response.getEntity().getContent();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    StringBuilder str = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        str.append(line);
    }
    in.close();
    html = str.toString();

but I'm getting error: Unhandled exception type ClientProtocolException and Unhandled exception type IOError on third line; and Unhandled exception type IOError on 6th, 10th and 13th line

I have also tried adding try/catch:

    try {
        HttpResponse response = client.execute(request);
    } catch (ClientProtocolException e) {
    } catch (IOException e) {
    }

but there's error on line InputStream in = response.getEntity().getContent(); saying response cannot be resolved

(I have Internet access allowed in Manifest)

Where's the problem? Thanks a lot

Upvotes: 0

Views: 473

Answers (2)

Eric Levine
Eric Levine

Reputation: 13564

The quick fix is to wrap your entire code block in the try/catch.

However, it will help you in the long run to understand exceptions in Java. When you catch an exception, you will want to handle it appropriately. A good place to start is here: http://download.oracle.com/javase/tutorial/essential/exceptions/

To solve the problem in your second example, you can do this:

HttpResponse response = null;
    try {
         client.execute(request);
    } catch (ClientProtocolException e) {
         //log the exception, throw it, etc...
    } catch (IOException e) {
      //log the exception, throw it, etc...
    }
   //if response != null, continue using it

Upvotes: 1

Rob
Rob

Reputation: 1152

Check out the JSoup cookbook.

http://jsoup.org/cookbook/

This has a lot of good information in it and should be able to answer most of your questions.

You are probably looking for something along the lines of this: http://jsoup.org/cookbook/input/parse-body-fragment

Upvotes: 0

Related Questions