How to use Jsoup with Volley?

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

Under the hood, Jsoup make use of HttpUrlConnection. This class has known unresolved issues, bugs and performance issues on the Android Platform.

Instead, load the data with Volley first then parse it with Jsoup.

Sample Code:

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];
}

References

Leave a Comment