如何在 Java 中加载维基百科页面

How to load a wikipedia page in Java

我正在尝试访问美国每个城市的维基百科页面。由于我不知道实际的 URL,我进行了搜索并加载了第一个结果。 URL 签名是:

http://en.wikipedia.org/wiki/Special:Search?go=Go&search=New+York%2C+NY

但是,它没有得到任何回复,这是我的代码:

String curWikiURL = "http://en.wikipedia.org/wiki/Special:Search?go=Go&search="+URLEncoder.encode("New York, NY", "UTF-8");;
Scanner scanner = null;
URLConnection connection = null;
connection =  new URL(curWikiURL).openConnection();
scanner = new Scanner(connection.getInputStream());
scanner.useDelimiter("\Z");
content = scanner.next();
Document doc = Jsoup.parse(content);

像下面这样使用它:

https://en.wikipedia.org/w/api.php?action=query&titles=Main%20Page&prop=revisions&rvprop=content&format=jsonfm 

这就是您使用 MediaWiki API 的方式。

点击此处了解更多详情 - https://www.mediawiki.org/wiki/API:Main_page

你不必做所有的连接和东西 JSoup 库可以处理下面的所有these.Check

String url = "https://en.wikipedia.org/w/api.php?action=query&titles=Main%20Page&prop=revisions&rvprop=content&format=jsonfm ";
    org.jsoup.nodes.Document document = (org.jsoup.nodes.Document) Jsoup
            .connect(url).followRedirects(false).timeout(60000).get();
    org.jsoup.select.Elements elements = ((org.jsoup.nodes.Document) document)
            .body().children();
for (Element element : elements) {
    System.out.println(element);
}