Minh Quang Ngo :
I want to get and extract the number after unixtime from this link. http://worldtimeapi.org/api/ip.txt I use below code to get data but seem it wrong
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();
Also, how can I test for network error by using mockito and Junit?
Jacob G. :
One solution is to use Java's HttpClient
to issue a GET
request to the URL and have it return a response as a String
. After that, you can use a simple regular expression to extract the value that you're looking for:
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));
}
Output:
1543639818
Just remember to handle any checked exceptions correctly.