package com.unbreakable.test;
import com.rometools.rome.feed.synd.SyndEntry;
import com.rometools.rome.feed.synd.SyndFeed;
import com.rometools.rome.io.SyndFeedInput;
import com.rometools.rome.io.XmlReader;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import javax.net.ssl.*;
import java.net.URL;
import java.security.cert.X509Certificate;
import java.util.List;
/**
* RSS 测试类
* 说明:通过 JUnit 运行测试方法 testFetchRssFeed()
* 或在类上右键 -> Run 'RssTest' (使用 JUnit 运行)
* 如果直接运行 main 方法,会执行测试逻辑并输出结果
*/
@SpringBootTest
public class RssTest {
public static final String RSS_URL = "https://www.stocktitan.net/rss";
/**
* 禁用 SSL 证书验证(仅用于测试环境,切勿在生产环境使用)
*/
@BeforeAll
public static void disableSSL() throws Exception {
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
// 不验证客户端证书
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
// 不验证服务端证书
}
}
};
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true);
}
/**
* 抓取 RSS 内容
*
* @param rssUrl RSS 订阅源地址
* @return 条目列表
* @throws Exception 网络或解析异常
*/
public List<SyndEntry> fetchRssFeed(String rssUrl) throws Exception {
URL url = new URL(rssUrl);
SyndFeedInput input = new SyndFeedInput();
// 使用 XmlReader 自动处理编码并读取 XML
SyndFeed feed = input.build(new XmlReader(url));
return feed.getEntries();
}
/**
* JUnit 测试方法:测试抓取 RSS 并打印
*/
@Test
public void testFetchRssFeed() throws Exception {
List<SyndEntry> list = this.fetchRssFeed(RSS_URL);
System.out.println("获取到 " + list.size() + " 条 RSS 条目");
for (SyndEntry entry : list) {
System.out.println("标题: " + entry.getTitle());
System.out.println("链接: " + entry.getLink());
System.out.println("发布时间: " + entry.getPublishedDate());
System.out.println("---");
}
}
/**
* 可选:main 方法,方便直接运行该类(不通过 JUnit)
* 此方法不是必须的,JUnit 测试应通过 JUnit 运行器执行。
*/
public static void main(String[] args) throws Exception {
RssTest test = new RssTest();
// 手动禁用 SSL(@BeforeAll 不会在 main 执行时自动调用,需要显式调用)
disableSSL();
test.testFetchRssFeed();
}
}
老师的那种,少些很多代码,还没有执行main方法;请赐教