【问题标题】:OpenWeatherMap API JavaOpenWeatherMap API Java
【发布时间】:2020-03-04 15:33:06
【问题描述】:

我正在做一个项目,我正在创建一个用于给植物浇水的 Java 应用程序。从在线获取天气信息并基于该输出的想法应该是我们的植物是否需要水。对于天气信息,我找到了API OpenWeatherMap,我尝试使用 YouTube 的教育视频来实现它。我过去没有使用 API 的经验。我正在使用的视频是“https://www.youtube.com/watch?v=og5h5ppwXgU”。我尝试以与那个人相同的方式实现我的程序,但我没有得到任何输出。它只是打印打印语句中的内容,而不是实际数据。

public static Map<String,Object> jsonToMap(String str){
    Map<String,Object> map = new Gson().fromJson(str,new 
TypeToken<HashMap<String,Object>> () {}.getType());
    return map;
}

   public static void  main(String[] args) {

      String API_KEY = "16 digit Private Key";
      String LOCATION = "Los Angeles,CA";
      String urlString = "http://api.openweathermap.org/data/2.5/weather? 
q=" + LOCATION + "&appid=" + API_KEY + "&units =imperial";



      try{

          StringBuilder result = new StringBuilder();
          URL url = new URL(urlString);
          URLConnection conn = url.openConnection();
          BufferedReader rd = new BufferedReader(new InputStreamReader (conn.getInputStream()));
          String line;
          while ((line = rd.readLine()) != null){
              result.append(line);
          }

          rd.close();
          System.out.println(result);

          Map<String, Object > respMap = jsonToMap (result.toString());
          Map<String, Object > mainMap = jsonToMap (respMap.get("main").toString());
          Map<String, Object > windMap = jsonToMap (respMap.get("wind").toString());

          System.out.println("Current Temperature: " + mainMap.get("temp")  );
          System.out.println("Current Humidity: " + mainMap.get("humidity")  );
          System.out.println("Wind Speed: " + windMap.get("speed")  );
          System.out.println("Wind Angle: " + windMap.get("deg")  );


      }catch (IOException e){
          System.out.println(e.getMessage());
      }



}

我收到 gson 库不存在的错误,但是在我使用 javadoc、类路径和源在 net beans 中创建我自己的库后,问题得到了解决,所以我认为是正确的。openweathermap 的 API 密钥也是也有效。我只是无法获取获取在线信息的代码。

输出:

http://api.openweathermap.org/data/2.5/weatherq=Losangeles,CA&appid="16 位私钥"&units =imperial

预期输出:洛杉矶当前天气信息

【问题讨论】:

  • 这是处理 API 的一种非常糟糕的方式(在这种情况下,它通常被称为使用 API)。您应该创建一个与 JSON 结构匹配的 POJO(或者如果您在数组中发送,则为列表项结构)。然后简单地反序列化它。这是一个教程:baeldung.com/gson-deserialization-guide

标签: java json api


【解决方案1】:

具有给定纬度和经度的 OpenWeatherMapApi 的实现。对于网络请求Retrofit & Jsonschema2pojo 来创建模型。 希望这会有所帮助。

public void getWeatherDetails(double latitude, double longitude) {

    String url = "http://api.openweathermap.org/";


    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(url) //This is the only mandatory call on Builder object.
            .addConverterFactory(GsonConverterFactory.create()) // Convertor library used to convert response into POJO
            .build();


    WeatherApiService weatherApiService = retrofit.create(WeatherApiService.class);

    weatherApiService.requestWeather(String.valueOf(latitude), String.valueOf(longitude), "metric", "10").enqueue(new UpasargaCallback<WeatherModel>() {
        @Override
        public void onResponse(Call<WeatherModel> call, Response<WeatherModel> response) {


            if (response.isSuccessful()) {

                if (response.body() != null) {
                    if (getView() != null) {

                        getView().onWeatherApiSuccess(response.body());
                    }


                }

            }

        }

        @Override
        public void onFailure(Call<WeatherModel> call, Throwable t) {
            if (getView() != null) {

                getView().onWeatherApiFailure(String.valueOf(t.getMessage()));
            }

        }
    });


}

WeatherApiService

public interface WeatherApiService {

    @Headers("x-api-key: " + AppConstants.WEATHER_API_KEY)
    @GET("data/2.5/forecast")
    Call<WeatherModel> requestWeather(@Query("lat") String lat,@Query("lon") String lon,@Query("units") String units,@Query("cnt") String count);
}

WeatherModel.java

【讨论】:

    【解决方案2】:

    我在浏览器中使用您的应用密钥测试了 API。它是成功的。也许你应该对你的 URL 进行编码。它有一个空格,这是一个特殊字符。

    【讨论】:

    • 谢谢。但我在“api.openweathermap.org/data/2.5/weather?q=”中没有看到任何空格。你能详细解释一下吗?
    • 我认为他们指的是您所在城市的空间。我还在浏览器中尝试了您的请求,但在我使用“los+angeles”作为查询之前它无法正常工作。
    • 您应该关心您的应用密钥,它是私有的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-04
    • 2018-06-05
    • 2021-12-31
    • 1970-01-01
    • 2017-02-08
    • 2021-06-12
    • 2016-03-23
    相关资源
    最近更新 更多