[英]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.