如何将 Jsoup 与 Volley 一起使用?

How to use Jsoup with Volley?

我有一个 Jsoup 和 AsyncTask 的工作示例,效果很好。我只是对表演不满意。加载包含文本和图像的简单列表页面需要 3-6 秒。

我想以某种方式提高性能...所以我无意中发现了截击。

谁能解释一下 hot 在 jsoup 中使用 volley 吗?

我用它来获取包含特定 URL:

的文档对象
 public Document GetDocument(String site) {      
        Document doc = Jsoup.connect(site).timeout(600000)
        .data("query", "Java")
        .userAgent("Mozilla")
        .get();

        return doc;
 }

我想我只会用 jsoup 和 connect/download 用 volley 分析数据?当我使用 Jsoup.connect(site).timeout(600000) 时,我应该使用 volley ?

谁能write/link一个使用 volley 和 jsoup 的简单例子?

Can anyone write/link a simple example using volley and jsoup?

在幕后,Jsoup 利用了 HttpUrlConnection。此 class 在 Android 平台上存在已知未解决的问题、错误和性能问题。

相反,首先使用 Volley 加载数据,然后使用 Jsoup 解析它。

示例代码:

private static RequestQueue myRequestQueue = null;

public Document GetDocument(String site) throws Exception {   
   final Document[] doc = new Document[1];
   final CountDownLatch cdl = new CountDownLatch(1);
 
   StringRequest documentRequest = new StringRequest( //
        Request.Method.GET, //
        site, //
        new Response.Listener<String>() {
           @Override
           public void onResponse(String response) {
               doc[0] = Jsoup.parse(response);
               cdl.countDown();
           }
        }, //
        new Response.ErrorListener() {
           @Override
           public void onErrorResponse(VolleyError error) {
               // Error handling
               System.out.println("Houston we have a problem ... !");
               error.printStackTrace();
           }
        } //
   );

   if (myRequestQueue == null) {
       myRequestQueue = Volley.newRequestQueue(this);
   }

   // Add the request to the queue...
   myRequestQueue.add(documentRequest);

   // ... and wait for the document.
   // NOTE: Be aware of user experience here. We don't want to freeze the app...
   cdl.await();

   return doc[0];
}

参考资料

根据 Stephan 的回答,我对这段代码做了一些小的修改,它看起来像这样。我添加了 UTF 8 支持,因此它可以读取其他语言并指定重试策略。

private static RequestQueue myRequestQueue = null;

public Document GetDocument(String site) {
    final Document[] doc = new Document[1];
    final CountDownLatch cdl = new CountDownLatch(1);
    try {

        StringRequest documentRequest = new StringRequest( //
                Request.Method.GET, //
                site, //
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        String newStr = null;
                        try {
                            newStr = URLDecoder.decode(URLEncoder.encode(response, "iso8859-1"), "UTF-8");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        doc[0] = Jsoup.parse(newStr);
                        cdl.countDown();
                    }
                }, //
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // Error handling
                        System.out.println("Houston we have a problem ... !");
                        error.printStackTrace();
                    }
                } //
        );

        if (myRequestQueue == null) {
            myRequestQueue = Volley.newRequestQueue(MainActivity._Instance);

            documentRequest.setRetryPolicy(new DefaultRetryPolicy(5000,
                    DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        }

        // Add the request to the queue...
        myRequestQueue.add(documentRequest);

        // ... and wait for the document.
        // NOTA: Be aware of user experience here. We don't want to freeze the app...
        cdl.await();
    }
    catch (Exception e) {
        Log.d("TMS", "Error parsing page " + site);
        e.printStackTrace();
        return null;
    }
    return doc[0];
}

将 Volley 添加到您的项目中。

implementation 'com.android.volley:volley:1.2.1'

然后使用下面的代码,

 runOnUiThread(() -> {
 // Stuff that updates the UI
 new Thread(() -> {
     
     final StringBuilder builder1 = new StringBuilder();
     
     String url = "your.url.com";                                   //RequestQueue initialized
     RequestQueue mRequestQueue = Volley.newRequestQueue(this);     //String Request initialized
     StringRequest mStringRequest = new StringRequest(Request.Method.GET, url, response -> {
     
     //Toast.makeText(getApplicationContext(),"Response :" + response.toString(), Toast.LENGTH_LONG).show();
     
     Document doc = Jsoup.parse(response);
     
     Elements trs = doc.select("table.content tr");
     
     for (Element tr : trs) 
         {
             Elements tds = tr.getElementsByTag("td");
             Element td = tds.get(0);
             builder1.append(td.text()).append(",");
         }
         
         String str1 = builder1.toString();
         
         runOnUiThread(() -> {
             String[] items1 = str1.split(",");
             int i = 1;
             while (i < items1.length) 
             {
                 //
                 i++;
             }
             });
             }, error -> Log.i(TAG,"Error :" + error.toString()));
            mRequestQueue.add(mStringRequest);
     }).start();
});