-4

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

是否有任何 API 可供使用?

4

1 回答 1

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 类中添加其他必要的字段(例如页面内容)。这只是一个例子。

于 2017-11-14T23:31:10.057 回答