java - OpenWeatherMap API Java

标签 java json api

我正在开发一个项目,我正在创建一个用于浇灌植物的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 key 也是也有效。我只是无法获取获取在线信息的代码。

输出:

http://api.openweathermap.org/data/2.5/weatherq=Los洛杉矶,CA&appid="16 位私钥"&单位=帝国

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

最佳答案

具有给定纬度和经度的 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

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

相关文章:

java - 在 View 绑定(bind)中返回 findViewById()

java jaxb eclipse

java - 实体参数的多态 JSON 反序列化 (Jackson) (Google Cloud Endpoints)

json - JWT(JSON Web token )是否有人嗅探 token ,是否可以发送相同的帖子?

c# - 触发操作系统以编程方式复制(ctrl+c 或 Ctrl-x)

php - 通过 Postman 使用 Magento API 通过 Oauth 1.0 授权

java - 如何使用两个分隔符拆分一个字符串,其中一个分隔符是双制表符?

javascript - 将 JSON 数据反序列化到字典 <string, string> 时出错

typescript - nest.js @Post设置响应的内容类型

java - uriBuilder 返回 http :/instead of http://