开发者

getting the html source code with a url in an android application

I have problems with getting the html source code with an url. I am trying to develop an开发者_运维知识库 application which takes in an url and upon the button submit by the user, it takes in the url and make calls to the url provided to retrieve the html source code.

I have looked up on various methods of doing it, but have always been presented with errors using the codes provided.

Listed below is one of the codes which I have used but it doesn't seem to work for me, it will throw a Error: null in the exception when I use logcat to debug.

please pardon me if the question sounds simple, I'm new to programming. thanks in advance.

String htmlCode = "";

    try {
    URL url = new URL("http://www.google.com/");
    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

    String inputLine;

    while ((inputLine = in.readLine()) != null)
        htmlCode += inputLine;

    in.close();
    } catch (Exception e) {
        Log.d(LOG_TAG, "Error: " + e.getMessage());
    }


That code seems to be functional and works for me. Can you post the exception/error you are getting when you run the code?


At a glance, the code looks fine. Make sure you add the Internet permission in your AndroidManifest.xml.

<uses-permission android:name="android.permission.INTERNET" />


I just ran this code and its working fine. The error must be coming from somewhere else?


Are you running this in the emulator? The emulator has DNS problems sometimes. It's possible the emulator can't find www.google.com, see this post:

Upgraded to SDK 2.3 - now no emulators have connectivity


a background process or use AsyncTask to perform your network transaction on a background thread will be required.

http://developer.android.com/resources/articles/painless-threading.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜