简体   繁体   中英

download html source android?

I'm trying to download a website source code and display it in a textbox but I seem to get an error and can't figure it out :s

 public void getHtml() throws ClientProtocolException, IOException
{
    HttpClient httpClient = new DefaultHttpClient();
    HttpContext localContext = new BasicHttpContext();
    HttpGet httpGet = new HttpGet("http://www.spartanjava.com");
    HttpResponse response = httpClient.execute(httpGet, localContext);
    String result = "";

    BufferedReader reader = new BufferedReader(
        new InputStreamReader(
          response.getEntity().getContent()
        )
      );

    String line = null;
    while ((line = reader.readLine()) != null){
      result += line + "\n";
      Toast.makeText(activity.this, line.toString(), Toast.LENGTH_LONG).show();

    }

}

how come this doesn't work and throw an IOException?

I think you're probably missing INTERNET permission in your manifest.xml Pay attention to <uses-permission> tag provided in the code below. I tested your code in eclipse, and it works.

BTW I think using String result in this way wont work. Didn't test that far though. But I think you cannot just add string to a string. You need to use stringBuilder and append new strings.

EDIT: tested this String result metod, and it works. Maybe the problem is that you are trying to throw so many toast all at once. Your code throws a toast for every line of retrived html code. I set your getHtml() method to type String, and to return result , and it returned it properly... I can't think of any other reason for exception, except missing INTERNET permission in your AndroidManifest.xml....

Cheers!

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="test.test.test"
  android:versionCode="1"
  android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="true">
    <activity android:name=".test"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
<uses-sdk android:minSdkVersion="3" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM