首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >OpenWeatherMap API

OpenWeatherMap API
EN

Stack Overflow用户
提问于 2019-11-08 01:24:39
回答 2查看 6.4K关注 0票数 0

我正在做一个项目,在这个项目中,我正在创建一个用于浇水的java应用程序,用于从网上获取天气信息。基于这个输出,如果我们植物需要水或not.For天气信息,我找到了一个API OpenWeatherMap,我尝试使用YouTube.I的教育视频来实现它。我对API的应用没有经验。我使用的视频是"https://www.youtube.com/watch?v=og5h5ppwXgU“.I试图像他那样实现我的程序,但我不会得到任何output.It只是打印打印声明中的内容,而不是实际数据。

代码语言:javascript
复制
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、类路径和soureces创建了自己的库之后,问题得到了解决,所以我认为openweathermap的correct.Also API密钥也是有效的,我只是无法获得获取在线信息的代码。

产出:

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

预期输出: LA的当前天气信息

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-11-08 01:37:34

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

票数 1
EN

Stack Overflow用户

发布于 2019-11-08 04:55:51

给定纬度和经度的OpenWeatherMapApi实现。对于网络请求改造Jsonschema2pojo创建模型。希望这能帮上忙。

代码语言:javascript
复制
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

代码语言:javascript
复制
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

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58759133

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档