import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class WeatherAPI {
private static final String BASE_URL = "http://api.map.baidu.com/weather/v1/";
private static final String AK = "your_access_key"; // 请替换成你自己的密钥
public static void main(String[] args) {
try {
String location = "上海"; // 要查询的位置
String encodedLocation = URLEncoder.encode(location, "UTF-8");
String apiUrl = BASE_URL + "?location=" + encodedLocation + "&ak=" + AK;
URL url = new URL(apiUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
System.out.println(response.toString());
} else {
System.out.println("HTTP请求失败,错误代码:" + responseCode);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}