简体   繁体   English

尝试使用AsyncTask和Jsoup从URL获取文本

[英]Trying to get text from an url with AsyncTask and Jsoup

The urls are just text files like www.example.com/example.txt so what I need to do is get the whole text from the website. 这些URL只是像www.example.com/example.txt这样的文本文件,因此我需要做的是从网站获取整个文本。 The text can be very long up to 1MB. 文本最长可能达到1MB。 I dont know how I should modify my code to do this. 我不知道该如何修改我的代码。

Here is my code 这是我的代码

private class Title extends AsyncTask<Void, Void, Void> {
    String text;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(Story.this);
        progressDialog.setMessage("Loading");
        progressDialog.setIndeterminate(false);
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    @Override
    protected Void doInBackground(Void... params) {
        try {
            Document document = Jsoup.connect(url).get();              
            text = document.text();    //I made this part up. Definitely WRONG
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {

        story.add(text);        //story is an array
        progressDialog.dismiss();
    }
}

I call it with new Title().execute(); 我用new Title().execute();称呼它new Title().execute();

This code doesn't work I cant get the text. 此代码不起作用,我无法获取文本。 Nothing happens. 什么都没发生。

What you should be doing is adding all of the Elements to an Elements object. 您应该做的是将所有Elements添加到Elements对象。 See below: 见下文:

@Override
protected Void doInBackground(Void... params) {
    try {
        Document document = Jsoup.connect(url).get();              
    } catch (IOException e) {
        e.printStackTrace();
    }
    Elements elem = null; 
    elem = document.select("*");
    Log.i("Value of elem", String.valueOf(elem);
    return null;
}

Then for your onPostExecute : 然后为您的onPostExecute

@Override
protected void onPostExecute(Void result) {
    String valueofelement = elem.text();
    story.add(valueofelement);        //story is an array
    progressDialog.dismiss();
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM