springboot调用第三方天气预报接口并以json格式显示给前端
时间: 2024-01-07 19:05:58 浏览: 80
1.添加依赖
```
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.1</version>
</dependency>
```
2.编写接口调用代码
```
@RestController
public class WeatherController {
@GetMapping("/weather")
public String getWeather() {
//调用第三方接口获取天气预报数据
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=your_api_key")
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
```
3.在application.properties中配置端口号
```
server.port=8080
```
4.启动应用,访问http://localhost:8080/weather即可获取天气预报数据以json格式返回给前端。需要替换your_api_key为你自己的API Key。
阅读全文