构建维基百科URL

时间:2017-11-14 23:22:21

标签: java api wikidata wikidata-api

如何用java语言构建维基百科URL? 例如,如果搜索“javascript”,则网址将为:https://en.wikipedia.org/wiki/JavaScript

是否有可以使用的API?

1 个答案:

答案 0 :(得分:1)

我不知道任何此类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();
    }
}

您的状态类:

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;
    }

这是主要的测试类:

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();
        }

    }

}

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