0

I want to get content of one page to String. I tried some ways to do it.

My code I tried to use:

    class GetWebContent extends AsyncTask<URL, String, String>{

    @Override
    protected String doInBackground(URL... url) {

        URL mypage = new URL(url[0]);  //HERE IS ERROR MalformedURLException
        StringBuilder sb = new StringBuilder();
        try {
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(
                            mypage.openStream()));

            String inputLine;

            while ((inputLine = in.readLine()) != null)
                sb.append(inputLine);


            in.close();
        } catch (IOException e) {
            Log.d("Exception",e.toString());
        }

        return sb.toString();

}

I edited code, so now I'm getting error java.net.MalformedURLException Thank you for your help.

ktos1234
  • 197
  • 1
  • 6
  • 22
  • http://stackoverflow.com/questions/6343166/how-to-fix-android-os-networkonmainthreadexception – CommonsWare Dec 05 '16 at 20:16
  • You said what's wrong. "Network on main thread exception". Google for it, and you'll know what to do. – Christine Dec 05 '16 at 20:17
  • @CommonWare , I follow the link you gave me, but I get error `java.net.MalformedURLException` when I try to declare URL. How to solve it? I edited my code. @Christine , I googled for it and google said It was wrong because I need to use AsyncTask. So I did, but still another error, and google has different answers... – ktos1234 Dec 05 '16 at 21:04
  • The given code cannot be correct because there is no constructor for `URL` that takes a single `URL`. If URL is actually `String` then `url[0]` being null would cause that exception. (Or providing a faulty URL) – Kiskae Dec 05 '16 at 21:11
  • @Kiskae there is constructor for `URL` that takes one parameter. I changed AsyncTask to `AsyncTask` . Can you tell me how to change this code that It could work? Thank you. – ktos1234 Dec 05 '16 at 21:25
  • Refer to http://stackoverflow.com/questions/29188557/download-file-with-asynctask for an example of downloading, the only thing you need to change it to store the output as a string, like your current solution does. – Kiskae Dec 05 '16 at 22:33
  • Thank you for research. My code just started working. I'm fighting with Jsoup now to remove html tags from downloaded content. Thank you for help. – ktos1234 Dec 05 '16 at 22:41
  • If you change your question, deleting lines, then the comments don't make sense any more. Please don't remove essential info from your question. – Christine Dec 06 '16 at 09:15

0 Answers0