Good day. I've defined a 2 URI
's for a http
call. The first one works great, the code is a complete copy beside some arguments. The second one throws a Exception
. I'll list the code below.
public class WeatherAPI {
private static String apiKey = "asdasd";
private HttpResponse<String> response;
private URI uri;
private HttpRequest getRequest(URI newUri) {
return HttpRequest.newBuilder()
.uri(newUri)
.build();
}
private HttpClient getClient() {
return HttpClient.newBuilder().build();
}
private String getResponse(URI uri) {
var client = getClient();
var request = getRequest(uri);
try {
response = client.send(request, HttpResponse.BodyHandlers.ofString());
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
return response.body();
}
public JSONObject getCityData(String lat, String lon) {
String url = "api.openweathermap.org/data/2.5/weather"; // System.out.println(uri);
try {
uri = new URIBuilder(URI.create(url))
.addParameter("lat", lat)
.addParameter("lon", lon)
.addParameter("appid", apiKey)
.build();
System.out.println(uri);
} catch (URISyntaxException e) {
e.printStackTrace();
}
var body = getResponse(uri);
System.out.println(body);
return null;
}
}
Throws
Exception in thread "main" java.lang.IllegalArgumentException: URI with undefined scheme
It seems that the URL is missing the protocol-Prefix like http:// or https:// .. try
http: //api.openweathermap.org/data/2.5/weather
or
https: //api.openweathermap.org/data/2.5/weather
as URL. This should work.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.