簡體   English   中英

如何使用Java從網站獲取和提取數字?

[英]How can I get and extract a number from website using Java?

我希望從此鏈接獲取並解壓縮 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測試網絡錯誤?

一種解決方案是使用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

請記住正確處理任何已檢查的異常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM