Open a connection with Jsoup, get status code and parse document

前端 未结 4 1102
春和景丽
春和景丽 2021-01-02 19:26

I\'m creating a class using jsoup that will do the following:

  1. The constructor opens a connection to a url.
  2. I have a method that will check the status
4条回答
  •  温柔的废话
    2021-01-02 19:59

    Seems your situation like you want to make connection with jsoup then check the status code and then according to the status code you will parse or whatever you want to do.

    For this first you have to check the status code of the URL instead creating connection.

      Response response = Jsoup.connect("Your Url ").followRedirects(false).execute();
            System.out.println(response.statusCode() + " : " + response.url());
    

    response.statusCode() will return you the status code

    After that you can create your connection

     if (200 == response.statusCode()) {
            doc = Jsoup.connect(" Your URL").get();
            Elements elements = doc.select("href");
            /* what ever you want to do*/
          }
    

    Your class will look like this

    package com.demo.soup.core;
    
    import java.io.IOException;
    
    import org.jsoup.Connection.Response;
    import org.jsoup.Jsoup;
    import org.jsoup.nodes.Document;
    
    /**
     * The Class DemoConnectionWithJsoup.
     *
     * @author Ankit Sood Apr 21, 2017
     */
    public class DemoConnectionWithJsoup {
    
        /**
         * The main method.
         *
         * @param args
         *            the arguments
         */
        public static void main(String[] args) {
        Response response;
        try {
            response = Jsoup.connect("Your URL ").followRedirects(false).execute();
    
            /* response.statusCode() will return you the status code */
            if (200 == response.statusCode()) {
            Document doc = Jsoup.connect("Your URL").get();
    
            /* what ever you want to do */
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    
        }
    
    }
    

提交回复
热议问题