1

I was wondering if is any way to get HTML code from any url and save that code as String in code? I have a method:

private String getHtmlData(Context context, String data){
    String head = "<head><style>@font-face {font-family: 'verdana';src: url('file://"+ context.getFilesDir().getAbsolutePath()+ "/verdana.ttf');}body {font-family: 'verdana';}</style></head>";
    String htmlData= "<html>"+head+"<body>"+data+"</body></html>" ;
    return htmlData;
 }

and I want to get this "data" from url. How I can do that?

edi233
  • 3,511
  • 13
  • 56
  • 97

3 Answers3

2

Try this (wrote it from the hand)

URL google = new URL("http://www.google.com/");
BufferedReader in = new BufferedReader(new InputStreamReader(google.openStream()));
String input;
StringBuffer stringBuffer = new StringBuffer();
while ((input = in.readLine()) != null)
{
    stringBuffer.append(input);
}
in.close();
String htmlData = stringBuffer.toString();
eMi
  • 5,540
  • 10
  • 60
  • 109
  • I get 06-10 10:43:45.094: E/AndroidRuntime(7210): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.fontfordroid/com.example.fontfordroid.MainActivity}: android.os.NetworkOnMainThreadException – edi233 Jun 10 '13 at 08:45
  • did you give your app internet permission? – eMi Jun 10 '13 at 08:56
  • its strange, I just tested it by myself and it works fine! Else take a look here: http://stackoverflow.com/questions/2423498/how-to-get-the-html-source-of-a-page-from-a-html-link-in-android – eMi Jun 10 '13 at 09:20
  • You paste this code in Thread or AsyncTask? I paste this code in onCreate. – edi233 Jun 10 '13 at 09:37
  • 1
    From API LEVEL 11, you cannot perform network related task on main thread, you have to do it in another thread. Otherwise you will get an exception "android.os.NetworkOnMainThreadException". – nikhil.thakkar Jun 10 '13 at 09:39
  • I'm using it in AsyncTask. Perform all the network related task in separate thread. Your problem should get solved. – eMi Jun 10 '13 at 09:41
1

Sure you can. That's actually the response body. You can get it like this:

HttpResponse response = client.execute(post);
String htmlPage = EntityUtils.toString(response.getEntity(), "ISO-8859-1");
Enrichman
  • 11,157
  • 11
  • 67
  • 101
0

take a look at this please, any other parser will work too, or you can even make your own checking the strings and retrieving just the part you want.

Community
  • 1
  • 1
Neron T
  • 369
  • 2
  • 8