如何使用Java从网站上获取和提取号码?

时间:2018-12-01 04:32:06

标签: java unit-testing

我想从此链接获取并提取 unixtime之后的数字。 http://worldtimeapi.org/api/ip.txt 我使用下面的代码获取数据,但似乎不对

  public String getData() throws IOException {
String httpUrl = "http://worldtimeapi.org/api/ip.txt";
URL url = new URL(httpUrl);
URLConnection urlConnection = url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String response = bufferedReader.readLine();
bufferedReader.close();

此外,如何使用Mockito和Junit测试网络错误?

1 个答案:

答案 0 :(得分:0)

一种解决方案是使用Java的HttpClient向URL发出GET请求,并使其以String的形式返回响应。之后,您可以使用简单的正则表达式提取所需的值:

Pattern pattern = Pattern.compile("unixtime: (\\d+)", Pattern.MULTILINE);

HttpClient client = HttpClient.newHttpClient();

HttpResponse<String> response = client.send(HttpRequest.newBuilder()
        .GET()
        .uri(new URI("http://worldtimeapi.org/api/ip.txt"))
        .build(), HttpResponse.BodyHandlers.ofString());

Matcher matcher = pattern.matcher(response.body());

if (matcher.find()) {
    System.out.println(matcher.group(1));
}

输出:

1543639818

请记住要正确处理所有检查的异常。