ミンクアンゴ:
私がしたい取得し、抽出し、このリンクから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を使用して、ネットワーク・エラーのためにテストすることができますか?
ジェイコブG.:
一つの解決策は、Javaのを使用することですHttpClient
発行するGET
URLへのリクエストをし、それのようにレスポンスを返す必要があり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
ただ、正確に任意のチェック例外を処理することを忘れないでください。