민 쾅 Ngo의 :
내가 원하는 얻을 추출 이 링크에서 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. :
하나 개의 솔루션은 자바를 사용하는 것입니다 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
그냥 정확히 어떤 검사 예외를 처리해야합니다.