建立维基百科 URL

Build a Wikipedia URL

如何用 java 语言构建 Wiki URL?

有API可以使用的吗?

我不知道有任何这样的 API。但是你可以创建自己的工厂方法:

    public class WikipediaURLFactory {

    private static final String WIKIPEDIA_BASE_URL = "https://en.wikipedia.org/wiki/";

    public static String createWikiURLString(String search) {
        return WIKIPEDIA_BASE_URL + search;
    }

    public static URL createWikiURL(String search) throws MalformedURLException {
        return new URL(createWikiURLString(search));
    }

    public static Status accessPage (URL url) throws IOException {
        Status status = new Status();
        status.setUrl(url);
        status.setExists(true);

        if (getResponseCode(url) == 404) {
            status.setExists(false);
        }

        return status; 
    }

    private static int getResponseCode (URL url) throws IOException {
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();

        return connection.getResponseCode();
    }
}

您的状态class:

private boolean exists;
    private URL url;

    public Status () {}

    public boolean isExists() {
        return exists;
    }

    public void setExists(boolean exists) {
        this.exists = exists;
    }

    public URL getUrl() {
        return url;
    }

    public void setUrl(URL url) {
        this.url = url;
    }

这里是主要测试 class:

public class Main {

    public static void main(String[] args) {

        try {

            // this will return true
            URL url = WikipediaURLFactory.createWikiURL("JavaScript");
            Status status = WikipediaURLFactory.accessPage(url);
            String negation = status.isExists() ? "" : "doesn't";
            System.out.println("The webpage " + url + " " + negation + " exist");

            // this will return false as page JafaScript doesn't exist on wiki
            url = WikipediaURLFactory.createWikiURL("JafaScript");
            status = WikipediaURLFactory.accessPage(url);
            negation = status.isExists() ? "" : "doesn't";
            System.out.println("The webpage " + url + " " + negation + " exist");

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

如果需要,您可以在状态 class 中添加其他必要字段(例如页面内容)。这只是一个例子。