Download html source android?

I'm trying to download the source code of a website and display it in a text box, but I seem to get an error message 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(); } } 

Why does this not work and throw an IOException?

+4
source share
1 answer

I think that you probably did not get INTERNET permission in your manifest. xml Pay attention to the <uses-permission> specified in the code below. I tested your code in eclipse and it works.

By the way, I think using String result this way will not work. Did not try this though. But I think you cannot just add a line to a line. You need to use stringBuilder and add new lines.

EDIT: Test this String result method and it works. Maybe the problem is that you are trying to throw so many toasts at once. Your code issues a toast for each line of the received html code. I set the getHtml() method for String input and returned result , and it returned it correctly ... I cannot think of any other reason for the exception, except for the lack of INTERNET permission in your AndroidManifest.xml ....

Hurrah!

 <?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> 

+2
source

Source: https://habr.com/ru/post/1313154/


All Articles