Непоследовательный отказ рукопожатия? - PullRequest
0 голосов
/ 28 января 2020

Итак, я работаю над программой для загрузки этих видео с веб-сайта. Первый и второй эпизоды успешно загружены, но затем, когда он добрался до третьего, он дал мне эту ошибку: javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure, что привело к сбою остальной части программы. Я не совсем уверен, почему он это делает, потому что он не выдает эту ошибку при подключении к предыдущим сайтам. Это также дает мне ошибку java.lang.NullPointerException. Я думаю, что эта вторая ошибка вызвана предыдущей ошибкой; он не может подключиться к веб-сайту, и нет информации для извлечения.

РЕДАКТИРОВАТЬ: Привет, извините, если я не достаточно ясно. Я не подключаюсь к одному и тому же URL 24 раза. Каждый URL - это отдельный веб-сайт с одинаковым макетом: название эпизода, ссылка на видео, кнопка следующего эпизода, кнопка предыдущего эпизода, раздел комментариев и т. Д. c. Он выглядит одинаково, потому что изменяется только один (иногда два) символа. Итак, я использую для l oop, и каждая итерация добавляет единицу к значению, переходя на следующий веб-сайт.

Как работает мой код:

1.) Создает список хранить каждый сайт. Он использует для l oop для добавления каждого веб-сайта в массив LinkedList типа String для упрощения управления URL.

2.) Получает первую ссылку из LinkedList, а затем подключается к ней.

3.) Получение ссылки IFrame (видео) из Списка; connects.

4.) Захватывает ссылку на страницу загрузки по ссылке Iframe; connects.

5.) Захватывает ссылку на скачивание с кнопки загрузки XSTREAM CDN.

6.) Захватывает прямую ссылку на скачивание с ссылки кнопки загрузки XSTREAM CDN.

7 .) Проверяет, существует ли файл, если он есть, в конце программы, если нет: переходите к шагу 8

8.) Создает JFrame с индикатором выполнения.

9.) Загрузки файл, используя Java .IO.

10.) Удаляет текущую ссылку из списка и добавляет 1 к значению для l oop, переходя к следующей ссылке. Повторяет шаги 2–10 еще 23 раза.

Пример:

Подключение к: https://swordartonlineepisode.com/sword-art-online-season-3-episode- 1 -engli sh -dubbed- watch-online /

Загружает файл, удаляет элемент из массива, добавляет 1, чтобы перейти к следующему эпизоду:

Соединяется с: https://swordartonlineepisode.com/sword-art-online-season-3-episode- 2 -engli sh -dubbed-watch-online /

Этот процесс продолжается 24 раза, каждый с различным URL.

Код:

package com.trentmenard;
import org.jsoup.*;
import org.jsoup.nodes.*;

import javax.swing.*;
import java.awt.*;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.LinkedList;

import static javax.swing.WindowConstants.EXIT_ON_CLOSE;

class WebsiteScraper {
    private Document websiteConnection;
    private String episodeName;
    private String iFrameLink;
    private String URLDownloadLink;
    private String URL;
    private static DecimalFormat decimalFormat = new DecimalFormat("#.##");


    WebsiteScraper(String URL) {
        LinkedList<String> episodeURLs = new LinkedList<>();

        for(int i = 1; i < 25; i++){
            episodeURLs.add("https://swordartonlineepisode.com/sword-art-online-season-3-episode-" + i + "-english-dubbed-watch-online/");
        }
        for(int x = 1; x < 25; x++){
            connectToURL("https://swordartonlineepisode.com/sword-art-online-season-3-episode-" + 2 + "-english-dubbed-watch-online/");
            episodeURLs.removeFirst();
        }
    }

    private void connectToURL(String URL) throws NullPointerException{
        try{
            websiteConnection = Jsoup.connect(URL).get();
            System.out.println("Connection Successfully Established to: " + URL);
        }catch (IOException e)
        {e.printStackTrace();}

        if(URL.equals(iFrameLink)){
            getDownloadLink();
        }
        else if(URL.equals(URLDownloadLink)) {
            getDirectDownloadLink();
        }
        if((URL.startsWith("https://swordartonlineepisode.com/sword-art-online-season-3-episode-"))){
            getEpisodeName();
        }
    }

    private void getEpisodeName(){
        Element h2 = websiteConnection.selectFirst("h2");
        episodeName = h2.text();
        System.out.println("Found Episode Name: " + episodeName);
        getIFrameLink();
    }

    private void getIFrameLink(){
        Element iFrame = websiteConnection.selectFirst("iframe");
        iFrameLink = iFrame.attr("src");
        System.out.println("Found iFrame Link: " + iFrameLink + " for: " + episodeName);
        connectToURL(iFrameLink);
    }

    private void getDownloadLink() {
        Element hiddenID = websiteConnection.getElementById("id");
        String hiddenIDValue = hiddenID.attr("value");
        URLDownloadLink = "https://www.vidstreaming.io/download?id=" + hiddenIDValue;
        System.out.println("Found Download Link Using ID Value (" + hiddenIDValue + "): " + URLDownloadLink);
        connectToURL(URLDownloadLink);
    }

    private void getDirectDownloadLink(){
        Element downloadClass = websiteConnection.getElementsContainingOwnText("Download (orginalP - mp4)").first();
        String directDownloadLink = downloadClass.attr("href");
        System.out.println("Found Direct Download Link: " + directDownloadLink);
        downloadEpisode(directDownloadLink, episodeName);
    }

    private void downloadEpisode(String URL, String episodeName) {
        this.URL = URL;
        float Percent = 0;
        String downloadProgress = "0.00";

        File createFile = new File(episodeName + ".mp4");
        if (createFile.exists() && !createFile.isDirectory()) {
            System.out.println("File: " + episodeName + " Already Exists! Moving Onto Next URL.");
        }
        else{
            JFrame progressFrame = new JFrame();
            JProgressBar progressBar = new JProgressBar(0, 100);

            progressBar.setSize(100, 100);
            progressBar.setValue(0);
            progressBar.setStringPainted(true);

            progressFrame.setTitle("Downloading: " + episodeName + " - " + Percent + "%");
            progressFrame.add(progressBar);
            progressFrame.setVisible(true);
            progressFrame.setLayout(new FlowLayout());
            progressFrame.setSize(575, 100);
            progressFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);

            JLabel percentComplete = new JLabel(downloadProgress + "% complete.");
            progressFrame.add(percentComplete);
            try {
                java.net.URL url = new URL(URL);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                System.out.println("Connection Successfully Established!");
                System.out.println("Downloading File: " + episodeName);

                int filesize = connection.getContentLength();
                float totalDataRead = 0;
                byte[] data = new byte[1024];
                int i;

                java.io.BufferedInputStream in = new java.io.BufferedInputStream(connection.getInputStream());
                java.io.FileOutputStream fos = new java.io.FileOutputStream(episodeName + ".mp4");
                java.io.BufferedOutputStream bout = new BufferedOutputStream(fos, 1024);

                while ((i = in.read(data, 0, 1024)) >= 0) {
                    totalDataRead = totalDataRead + i;
                    bout.write(data, 0, i);
                    Percent = (totalDataRead * 100) / filesize;
                    decimalFormat.setRoundingMode(RoundingMode.CEILING);
                    downloadProgress = decimalFormat.format(Percent);

                    progressFrame.setTitle("Downloading: " + episodeName);
                    progressBar.setValue((int) Percent);
                    percentComplete.setText(downloadProgress);
                }
                bout.close();
                in.close();
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("Connection Failed!");
            }
        }
    }
}

Вывод:

Connection Successfully Established to: https://swordartonlineepisode.com/sword-art-online-season-3-episode-2-english-dubbed-watch-online/
Found Episode Name: Sword Art Online Season 3 Episode 2 English Dubbed
Found iFrame Link: https://vidstreaming.io/streaming.php?id=MTEzNjg2 for: Sword Art Online Season 3 Episode 2 English Dubbed
Connection Successfully Established to: https://vidstreaming.io/streaming.php?id=MTEzNjg2
Found Download Link Using ID Value (MTEzNjg2): https://www.vidstreaming.io/download?id=MTEzNjg2
Connection Successfully Established to: https://www.vidstreaming.io/download?id=MTEzNjg2
Found Direct Download Link: https://st1x.cdnfile.info/user1342/1f1b04321e51fac1c1d1c23a1de4f7f0/EP.2.mp4?token=2NrGYWelERXELxg3WJmVPg&expires=1580203547&id=113686&title=(orginalP - mp4) Sword+Art+Online%3A+Alicization+%28Dub%29+Episode+2
File: Sword Art Online Season 3 Episode 2 English Dubbed Already Exists! Moving Onto Next URL.
javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
    at java.base/sun.security.ssl.Alert.createSSLException(Alert.java:128)
    at java.base/sun.security.ssl.Alert.createSSLException(Alert.java:117)
    at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:308)
    at java.base/sun.security.ssl.Alert$AlertConsumer.consume(Alert.java:279)
    at java.base/sun.security.ssl.TransportContext.dispatch(TransportContext.java:181)
    at java.base/sun.security.ssl.SSLTransport.decode(SSLTransport.java:164)
    at java.base/sun.security.ssl.SSLSocketImpl.decode(SSLSocketImpl.java:1152)
    at java.base/sun.security.ssl.SSLSocketImpl.readHandshakeRecord(SSLSocketImpl.java:1063)
    at java.base/sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:402)
    at java.base/sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:567)
    at java.base/sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
    at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:163)
    at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:730)
    at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:705)
    at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:295)
    at org.jsoup.helper.HttpConnection.get(HttpConnection.java:284)
    at com.trentmenard.WebsiteScraper.connectToURL(WebsiteScraper.java:41)
    at com.trentmenard.WebsiteScraper.<init>(WebsiteScraper.java:34)
    at com.trentmenard.Main.main(Main.java:6)
Exception in thread "main" java.lang.NullPointerException
    at com.trentmenard.WebsiteScraper.getEpisodeName(WebsiteScraper.java:59)
    at com.trentmenard.WebsiteScraper.connectToURL(WebsiteScraper.java:53)
    at com.trentmenard.WebsiteScraper.<init>(WebsiteScraper.java:34)
    at com.trentmenard.Main.main(Main.java:6)

Process finished with exit code 1

1 Ответ

0 голосов
/ 29 января 2020

Ни один из этих URL-адресов не позволяет загружать ... НИ ОДИН из них!

import Torello.HTML.*;
import Torello.HTML.NodeSearch.*;
import Torello.Java.*;

import java.util.*;
import java.io.*;
import java.net.*;

import java.math.RoundingMode;
import java.text.DecimalFormat;

public class WebsiteScraper
{
    @SuppressWarnings("unchecked")
    public static void main(String[] argv) throws IOException
    {
        // getURLs(); // Commented out because it has already run!

        String[][] urls = (String[][]) FileRW.readObjectFromFileNOCNFE("savedURLs.arrdat", true);
        for (int season=1; season <= 3; season++) for (int episode=1; episode <= 24; episode++)
            try
            { downloadEpisode(urls[season-1][episode-1], "S" + StringParse.zeroPad10e2(season) + "E" + StringParse.zeroPad10e2(episode)); }
            catch (Exception e)
            {
                String message = HTTPCodes.convertMessage(e);
                if (message != null)    System.out.println("Failed: " + message         + "\nSkipping...");
                else                    System.out.println("Failed: " + e.getMessage()  + "\nSkipping...");
            }
        // downloadEpisode("https://vidstreaming.io/streaming.php?id=MTIxMTEw", "name");
    }

    public static void getURLs() throws IOException
    {
        String[][] urls = new String[3][];
        urls[0] = new String[24];       urls[1] = new String[24];       urls[2] = new String[24];

        for (int season=1; season <= 3; season++) for (int episode=1; episode <= 24; episode++) 
        {
            URL                 url     = new URL("https://swordartonlineepisode.com/sword-art-online-season-" + season + "-episode-" + episode + "-english-dubbed-watch-online/");
            Vector<HTMLNode>    page    = HTMLPage.getPageTokens(url, false);
            TagNode             iFrame  = TagNodeGet.first(page, TC.OpeningTags, "iframe");
            String              src     = iFrame.AV("src");
            urls[season-1][episode-1] = src;
        }
        FileRW.writeObjectToFileNOCNFE(urls, "savedURLs.arrdat", true);
        for (int season=1; season <= 3; season++) for (int episode=1; episode <= 24; episode++)
            System.out.println("S" + StringParse.zeroPad10e2(season) + "E" + StringParse.zeroPad10e2(episode) + ": " + urls[season-1][episode-1]);
    }

    private static void downloadEpisode(String URL, String episodeName) throws IOException
    {
        float           Percent             = 0;
        String          downloadProgress    = "0.00";
        File            createFile          = new File(episodeName + ".mp4");
        DecimalFormat   decimalFormat = new DecimalFormat("#.##");

        decimalFormat.setRoundingMode(RoundingMode.CEILING);

        URL                 url         = new URL(URL);
        HttpURLConnection   connection  = (HttpURLConnection) url.openConnection();

        System.out.println("Connection Successfully Established!");
        System.out.println("Downloading File: " + episodeName);

        int     filesize        = connection.getContentLength();
        float   totalDataRead   = 0;
        byte[]  data            = new byte[1024];
        int     i;

        BufferedInputStream     in      = new java.io.BufferedInputStream(connection.getInputStream());
        FileOutputStream        fos     = new java.io.FileOutputStream(episodeName + ".mp4");
        BufferedOutputStream    bout    = new BufferedOutputStream(fos, 1024);

        while ((i = in.read(data, 0, 1024)) >= 0)
        {
            bout.write(data, 0, i);
            System.out.println('\r' + decimalFormat.format(((totalDataRead += i) * 100) / filesize));
        }
        bout.close();       in.close();
    }
}

Первый метод (получить URL-адреса) производит этот вывод ....

S01E01: https://vidstreaming.io/streaming.php?id=OTAyMTk
S01E02: https://vidstreaming.io/streaming.php?id=OTAyMjA
S01E03: https://vidstreaming.io/streaming.php?id=OTAyMjE
S01E04: https://vidstreaming.io/streaming.php?id=OTAyMjI
S01E05: https://vidstreaming.io/streaming.php?id=OTAyMjM
S01E06: https://vidstreaming.io/streaming.php?id=OTAyMjQ
S01E07: https://vidstreaming.io/streaming.php?id=OTAyMjU
S01E08: https://vidstreaming.io/streaming.php?id=OTAyMjY
S01E09: https://vidstreaming.io/streaming.php?id=OTAyMjc
S01E10: https://vidstreaming.io/streaming.php?id=OTAyMjg
S01E11: https://vidstreaming.io/streaming.php?id=OTAyMjk
S01E12: https://vidstreaming.io/streaming.php?id=OTAyMzE
S01E13: https://vidstreaming.io/streaming.php?id=OTAyMzA
S01E14: https://vidstreaming.io/streaming.php?id=OTAyMzI
S01E15: https://vidstreaming.io/streaming.php?id=OTAyMzM
S01E16: https://vidstreaming.io/streaming.php?id=OTAyMzQ
S01E17: https://vidstreaming.io/streaming.php?id=OTAyMzU
S01E18: https://vidstreaming.io/streaming.php?id=OTAyMzY
S01E19: https://vidstreaming.io/streaming.php?id=OTAyMzc
S01E20: https://vidstreaming.io/streaming.php?id=OTAyMzg
S01E21: https://vidstreaming.io/streaming.php?id=OTAyMzk
S01E22: https://vidstreaming.io/streaming.php?id=OTAyNDA
S01E23: https://vidstreaming.io/streaming.php?id=OTAyNDE
S01E24: https://vidstreaming.io/streaming.php?id=OTAyNDI
S02E01: https://vidstreaming.io/streaming.php?id=OTAyNDQ
S02E02: https://vidstreaming.io/streaming.php?id=OTAyNDU
S02E03: https://vidstreaming.io/streaming.php?id=OTAyNDY
S02E04: https://vidstreaming.io/streaming.php?id=OTAyNDc
S02E05: https://vidstreaming.io/streaming.php?id=OTAyNDg
S02E06: https://vidstreaming.io/streaming.php?id=OTAyNDk
S02E07: https://vidstreaming.io/streaming.php?id=OTAyNTA
S02E08: https://vidstreaming.io/streaming.php?id=OTAyNTE
S02E09: https://vidstreaming.io/streaming.php?id=OTAyNTI
S02E10: https://vidstreaming.io/streaming.php?id=OTAyNTM
S02E11: https://vidstreaming.io/streaming.php?id=OTAyNTQ
S02E12: https://vidstreaming.io/streaming.php?id=OTAyNTU
S02E13: https://vidstreaming.io/streaming.php?id=OTAyNTY
S02E14: https://vidstreaming.io/streaming.php?id=OTAyNTc
S02E15: https://vidstreaming.io/streaming.php?id=OTAyNTg
S02E16: https://vidstreaming.io/streaming.php?id=OTAyNTk
S02E17: https://vidstreaming.io/streaming.php?id=OTAyNjA
S02E18: https://vidstreaming.io/streaming.php?id=OTAyNjE
S02E19: https://vidstreaming.io/streaming.php?id=OTAyNjI
S02E20: https://vidstreaming.io/streaming.php?id=OTAyNjM
S02E21: https://vidstreaming.io/streaming.php?id=OTAyNjQ
S02E22: https://vidstreaming.io/streaming.php?id=OTAyNjU
S02E23: https://vidstreaming.io/streaming.php?id=OTAyNjY
S02E24: https://vidstreaming.io/streaming.php?id=OTAyNjc
S03E01: https://vidstreaming.io/streaming.php?id=MTEzMzQ1
S03E02: https://vidstreaming.io/streaming.php?id=MTEzNjg2
S03E03: https://vidstreaming.io/streaming.php?id=MTE0MDAx
S03E04: https://vidstreaming.io/streaming.php?id=MTE0NTYx
S03E05: https://vidstreaming.io/streaming.php?id=MTE1MDgx
S03E06: https://vidstreaming.io/streaming.php?id=MTE1Mzk3
S03E07: https://vidstreaming.io/streaming.php?id=MTE2MTk2
S03E08: https://vidstreaming.io/streaming.php?id=MTE2MTk3
S03E09: https://vidstreaming.io/streaming.php?id=MTE2MzM1
S03E10: https://vidstreaming.io/streaming.php?id=MTE2OTM4
S03E11: https://vidstreaming.io/streaming.php?id=MTE3NDg3
S03E12: https://vidstreaming.io/streaming.php?id=MTE4MzEz
S03E13: https://vidstreaming.io/streaming.php?id=MTE4ODI5
S03E14: https://vidstreaming.io/streaming.php?id=MTE5Mjkw
S03E15: https://vidstreaming.io/streaming.php?id=MTE5ODQz
S03E16: https://vidstreaming.io/streaming.php?id=MTIwNDUw
S03E17: https://vidstreaming.io/streaming.php?id=MTIxMTEw
S03E18: https://vidstreaming.io/streaming.php?id=MTIxNzIx
S03E19: https://vidstreaming.io/streaming.php?id=MTIyMjE5
S03E20: https://vidstreaming.io/streaming.php?id=MTIyNjQ1
S03E21: https://vidstreaming.io/streaming.php?id=MTIzMTI4
S03E22: https://vidstreaming.io/streaming.php?id=MTIzNzY1
S03E23: https://vidstreaming.io/streaming.php?id=MTI0MDcw
S03E24: https://vidstreaming.io/streaming.php?id=MTI0NTIx

К сожалению , это просто не будет загружаться с использованием вашей версии загрузчика .... Я попробовал свою собственную версию (см. Torello. Java .CURL), и он вернул HTTP-код 552 (не спрашивайте снова!)

Connection Successfully Established!
Downloading File: S01E01
Failed: HTTP-403: [Forbidden], Category: Client errors
Skipping...
Connection Successfully Established!
Downloading File: S01E02
Failed: HTTP-403: [Forbidden], Category: Client errors
Skipping...
Connection Successfully Established!
Downloading File: S01E03
Failed: HTTP-403: [Forbidden], Category: Client errors
Skipping...
Connection Successfully Established!
Downloading File: S01E04
Failed: HTTP-403: [Forbidden], Category: Client errors
Skipping...
Connection Successfully Established!
Downloading File: S01E05
Failed: HTTP-403: [Forbidden], Category: Client errors
Skipping...
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...