java获取天气信息
- 注册后获取API Key
java
https://www.visualcrossing.com/
- 引入依赖
java
<dependencies>
<!-- HTTP 请求 -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<!-- CSV 解析 -->
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>5.5.2</version>
</dependency>
<!-- Excel 生成 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.2</version>
</dependency>
</dependencies>
- demo
java
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import com.opencsv.CSVReader;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class RainfallFetcher {
public static void main(String[] args) throws Exception {
String apiKey = "RM3T8MSZBZL4H6E7TAXQYZ6MW";
// 使用坐标:纬度36.8556,经度114.5030,逗号必须URL编码成%2C
String location = "36.8556%2C114.5030";
String startDate = "2024-06-16";
String endDate = "2025-06-16";
String urlStr = String.format(
"https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/%s/%s/%s?unitGroup=metric&elements=datetime,precip&include=days&key=%s&contentType=csv",
location, startDate, endDate, apiKey);
System.out.println("请求URL: " + urlStr);
try (
InputStream inputStream = new URL(urlStr).openStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
CSVReader csvReader = new CSVReader(inputStreamReader);
Workbook workbook = new XSSFWorkbook();
FileOutputStream fileOut = new FileOutputStream("Shahe_Rain_Over_5mm.xlsx")
) {
String[] header = csvReader.readNext(); // 读取表头 ["datetime", "precip"]
Sheet sheet = workbook.createSheet("降雨≥5mm");
Row headerRow = sheet.createRow(0);
for (int i = 0; i < header.length; i++) {
headerRow.createCell(i).setCellValue(header[i]);
}
int rowIndex = 1;
String[] line;
while ((line = csvReader.readNext()) != null) {
double precip = Double.parseDouble(line[1]);
if (precip >= 5.0) {
Row row = sheet.createRow(rowIndex++);
row.createCell(0).setCellValue(line[0]);
row.createCell(1).setCellValue(precip);
}
}
workbook.write(fileOut);
System.out.println("导出完成,共找到 " + (rowIndex - 1) + " 天降雨≥5mm。");
}
}
}
通过java代码可以直接获取到csv文件。不过我使用的是将打印出来的完整请求地址,放入到postman中,使用postman来进行调用获取返回值