java - Spring boot - WeatherApp - API

标签 java spring api

我正在尝试使用 Spring Boot MVC 制作天气应用程序。我想使用来自 openweather.com 的 api。

在 Controller 中我有一个传递参数的方法。我有两个 html 页面。一个用于表单和提交,另一个用于显示表单的字符串。 如何将 API 与表单中的参数绑定(bind)以及如何检索 JSON 信息。

@GetMapping("/show")
public String show(@RequestParam ("city") String city, ModelMap modelMap){
    modelMap.addAttribute("city", city);
    return "article/show";
}

最佳答案

您的后端代码中应该有一个 get 监听器,用于从 openweather 获取天气。它应该看起来像这样:

@RequestMapping("/weather")
public String show(@RequestParam ("city") String city)
//Method body
//In the method body you should make a request to the openweather server with an api key which you can get by registering in the website. You can achieve this with Unirest library (it's the easiest way)
HttpResponse<JsonNode> response = Unirest.get("http://api.openweathermap.org/data/2.5/weather")/
                            .queryString("APPID","YOUR_APP_ID")
                            .queryString("city",city)
                            .header("content-type","application/json")
                            .asJson();

此方法将返回一个包含您需要的所有数据的 JSON,您可以使用 RestTemplate 对其进行解析。

关于java - Spring boot - WeatherApp - API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46116761/

相关文章:

java - Spring中如何根据配置创建多个相同类型的bean?

java - 它的用途 <sf :errors path ="" cssClass ="error"> in jsp?

javascript - 将任何 Nodejs 请求转发到其他服务器

java - Spring 方面记录器

java - Hibernate不保存时间戳字段

java - Controller Java 上的 Spring 单元测试

javascript - Backbone REST API推荐/跨域

api - 如果第 3 方 API 身份验证失败,我的 API 应该返回哪些 HTTP 错误代码?

java - 我正在用 Java 编写屏幕捕获模块,但在将屏幕截图写入磁盘时遇到严重的性能问题。我还可以做些什么?

java - 将独立状态设置为 Java 枚举值