首页 > 解决方案 > java接收html网页时出错

问题描述

下面的代码用于获取 html 网页

import java.net.*;
import java.io.*;
import java.io.File;  // Import the File class
import java.io.IOException;  // Import the IOException class to handle errors

public class TestClass2 {
    
  public static void main(String[] args) throws Exception {


 
    try{
      URL url = new URL("https://stackoverflow.com/");
      
      HttpURLConnection urlConnection=(HttpURLConnection)url.openConnection(); 

      BufferedReader reader = new BufferedReader( new InputStreamReader(url.openStream()));
      String line;
      while ((line = reader.readLine()) != null)
      {
        System.out.println(line+"\n");
      }
      reader.close();
    }catch(Exception ex){
      System.out.println(ex);
    }
    
  }
}


但是在编译和运行时会出现以下错误:

javax.net.ssl.SSLException:收到致命警报:protocol_version。

如何解决?谢谢。

标签: javahtmlssl

解决方案


这可能是 SSL 证书已过期?您是否尝试过使用 HttpsURLConnection?先试试这个

修订代码

import java.net.*;
import java.io.*;
import java.io.File;  // Import the File class
import java.io.IOException;  // Import the IOException class to handle errors

public class TestClass2 {
    
  public static void main(String[] args) throws Exception {


 
    try{
      URL url = new URL("https://stackoverflow.com/");
      
      HttpsURLConnection urlConnection=(HttpsURLConnection)url.openConnection(); 

      BufferedReader reader = new BufferedReader( new InputStreamReader(url.openStream()));
      String line;
      while ((line = reader.readLine()) != null)
      {
        System.out.println(line+"\n");
      }
      reader.close();
    }catch(Exception ex){
      System.out.println(ex);
    }
    
  }
} 

推荐阅读