Java Ошибка проверки подлинности веб-проверки - NoClassDefFound & ClassNotFound - PullRequest
0 голосов
/ 06 февраля 2020

Впервые на слом - я пытаюсь удалить теги компании Leetcode.com, используя Java, и поскольку для Leetcode.com вопросы под тегами компании доступны только для премиум-пользователей, мне нужно войти на сайт первый. Я создал класс для веб-аутентификации под названием LeetcodeClient, при попытке инициализировать его я получил ошибки ClassNotFound и NoClassDefFound. Вот мой код:

LeetCodeScrapingModel. java (V в MVC)

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashSet;


public class LeetcodeScrapingModel {
    */**
     * Arguments.
     *
     * @param c1 The first company to search questions for.
     * @param c2 The second company to search questions for.
     * @return the integer array that contains the question numbers of the common questions between the two companies.
     */*
    public int[] findCommonQuestion(String c1, String c2) throws UnsupportedEncodingException  {
        //Create a new LeetcodeClient and log us in
        LeetcodeClient client = new LeetcodeClient("username", "password");
        client.login();
        /*
         * URL encode the searchTag, e.g. to encode spaces as %20
         *
         * There is no reason that UTF-8 would be unsupported.  It is the
         * standard encoding today.  So if it is not supported, we have
         * big problems, so don't catch the exception.
         */
        c1 = URLEncoder.encode(c1, "UTF-8");
        c2 = URLEncoder.encode(c2, "UTF-8");


        // Create a URL for the page to be screen scraped
        String c1URL = "https://leetcode.com/company/" + c1;
        String c2URL = "https://leetcode.com/company/" + c2;

        // Fetch the page
        String c1response = client.get("https://leetcode.com/company/" + c1);
        String c2response = client.get("https://leetcode.com/company/" + c2);

LeetcodeClient. java

import java.io.IOException;
import java.net.MalformedURLException;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;

public class LeetcodeClient {
    //Create a new WebClient with any BrowserVersion. WebClient belongs to the
    //HtmlUnit library.
    private WebClient WEB_CLIENT = null;

    //Leetcode credentials.
    private String username = null;
    private String password = null;

    //Constructor. Sets our username and password and does some client config.
    public LeetcodeClient(String username, String password){
        WEB_CLIENT = new WebClient(BrowserVersion.CHROME);
        this.username = username;
        this.password = password;

        //Retreives our WebClient's cookie manager and enables cookies.
        //This is what allows us to view pages that require login.
        //If this were set to false, the login session wouldn't persist.
        WEB_CLIENT.getCookieManager().setCookiesEnabled(true);
    }

    public void login(){
        //This is the URL where we log in, easy.
        String loginURL = "https://leetcode.com/accounts/login";
        try {

            //Create an HtmlPage and get the login page.
            HtmlPage loginPage = WEB_CLIENT.getPage(loginURL);

            //Create an HtmlForm by locating the form that pertains to logging in.
            HtmlForm loginForm = loginPage.getFirstByXPath("//form[@class='form__2-sN']");

            //This is where we modify the form. The getInputByName method looks
            //for an <input> tag with some name attribute. For example, user or passwd.
            //If we take a look at the form, it all makes sense.
            //<input value="" name="user" id="user_login" ...
            //"Find the <input> tags with the names "user" and "passwd"
            //and throw in our username and password in the text fields.
            loginForm.getInputByName("login").setValueAttribute(username);
            loginForm.getInputByName("password").setValueAttribute(password);
            loginForm.getElementsByTagName("button").get(0).click();

        } catch (FailingHttpStatusCodeException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String get(String URL){
        try {
            //All this method does is return the HTML response for some URL.
            //We'll call this after we log in!
            return WEB_CLIENT.getPage(URL).getWebResponse().getContentAsString();
        } catch (FailingHttpStatusCodeException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

Вот ошибка, которую я получил после того, как ввел названия обеих компаний: enter image description here

Ошибка появилась в этой строке LeetcodeClient client = new LeetcodeClient("username", "password"); модели . java файл. Я попытался переместить класс LeecodeClient в файл модели как частный класс, но это не сработало - я не уверен, почему он выдает мне ошибку ClassNotFound И NoClassDefFound ... оба файла находятся в одном и том же файле sr c папка FYI.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...