市场上有许多免费的和付费的天气预报API,例如OpenWeatherMap、WeatherAPI、Weatherstack等。这里我们以OpenWeatherMap为例,因为它提供了广泛的天气数据和相对简单的API接口。
访问OpenWeatherMap的官网(https://openweathermap.org/) ,注册一个账户,并创建一个API密钥(APIkey)。这个密钥将用于你的请求中,以验证身份和访问权限。
可以使用java.net.HttpURLConnection
,或者Apache HttpClient、OkHttp等来调用接口。
1.使用java.net.HttpURLConnection
来调用OpenWeatherMap API获取天气预报的:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class WeatherClient {
public static void main(String[] args) {
try {
String apiKey = "你的API密钥";
String cityName = "Beijing";
String urlString = "http://api.openweathermap.org/data/2.5/weather?q=" + cityName + "&appid=" + apiKey + "&units=metric";
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/json");
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new RuntimeException("Failed : HTTP error code : " + connection.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((connection.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
2.使用OkHttp库示例:
OkHttpClient client = new OkHttpClient();
String url = "http://api.openweathermap.org/data/2.5/weather?q=" + cityName + "&appid=" + apiKey + "&units=metric";
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
标签:java,webservice,connection,API,new,天气预报,HttpURLConnection,String From: https://blog.51cto.com/u_15266301/12121640