kymbrik
11/10/2017 - 1:38 PM

Check response code Java Jsoup

В API WebDriver нет возможности проверить Response Code. Поэтому, нужно использовать Jsoup, чтобы убедиться, что данную страницу я смогу извлечь.

https://stackoverflow.com/questions/10518972/open-a-connection-with-jsoup-get-status-code-and-parse-document

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();
    }

    }