mH16 mH16 - 1 year ago 135
Android Question

How to get HTML source code from url in android?

I am working on project to get html source code in a string in using dom parser to get source code of a page.

1) I want to implement the same in android, what will be the approach to get source code of webpage by calling a url in android.
2) I would be having two layouts for source code in one layout and other for the webpage itself. If i am changing title tag value in source code layout, its must be automatically updated on actual webpage ?

What would be the best approach to do that in android ?

Any kind of help will be highly appreciated.

Answer Source

In order to get your source code from an URL you can use this :

HttpClient httpclient = new DefaultHttpClient(); // Create HTTP Client
HttpGet httpget = new HttpGet(""); // Set the action you want to do
HttpResponse response = httpclient.execute(httpget); // Executeit
HttpEntity entity = response.getEntity(); 
InputStream is = entity.getContent(); // Create an InputStream with the response
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) // Read line by line
    sb.append(line + "\n");

String resString = sb.toString(); // Result is here

is.close(); // Close the stream

You can also add some params to the HttpClient to manage timeout and other stuff like that. Ex :

HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters,3000); // 3s max for connection
HttpConnectionParams.setSoTimeout(httpParameters, 4000); // 4s max to get data
HttpClient httpclient = new DefaultHttpClient(httpParameters);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download