如何解决使用retrofit2使用纬度和经度从openweathermap 解析数据
我一直在尝试使用用户当前位置(即纬度和经度)使用 openweathermap api 获取天气,我已经正确检索了协调但当我运行应用程序时,我在 logcat 中收到错误 404。这是我的代码
private void setData(double latitude,double longitude) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.openweathermap.org/data/2.5/")
.addConverterFactory(GsonConverterFactory.create())
.build();
WeatherAPI api = retrofit.create(WeatherAPI.class);
Integer latitudeInt = (int) latitude;
Integer longitudeInt = (int) longitude;
Log.v("LATITUDE STRING",String.valueOf(latitudeInt));
Log.v("LONGITUDE STRING",String.valueOf(longitudeInt));
Call<WeatherResponse> call = api.getCurrentWeatherData(String.valueOf(latitudeInt),String.valueOf(longitudeInt),appId);
call.enqueue(new Callback<WeatherResponse>() {
@Override
public void onResponse(Call<WeatherResponse> call,Response<WeatherResponse> response) {
Log.v("RESPONSE",String.valueOf(response.code()));
if (response.code() == 200) {
WeatherResponse weatherResponse = response.body();
assert weatherResponse != null;
double temp = weatherResponse.main.getTemp() - 273.15;
mainWeather.setText(String.valueOf(temp));
SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
Date currentDate = new Date(System.currentTimeMillis());
String dateString = formatter.format(currentDate);
date.setText(dateString);
double wind = weatherResponse.wind.getSpeed() * 2.23;
windSpeed.setText(String.valueOf(wind));
pressure.setText(String.valueOf(weatherResponse.main.getPressure()));
humidity.setText(String.valueOf(weatherResponse.main.getHumidity()));
feelsLike.setText(String.valueOf(weatherResponse.main.getFeelsLike()));
setImage(weatherResponse);
}
}
@Override
public void onFailure(Call<WeatherResponse> call,Throwable t) {
mainWeather.setText("Error!");
}
});
}
这里是查询的WeatherApi接口
public interface WeatherAPI {
@GET("data/2.5/weather?")
Call<WeatherResponse> getCurrentWeatherData(@Query("lat") String lat,@Query("lon") String lon,@Query("APPID") String app_id);
}
我已经从我的其他天气应用程序之一复制了数据类,该应用程序使用用户的城市输入来显示天气并且运行良好,但该应用程序根本没有填充视图。在 logcat 中,我收到错误 404。
解决方法
您好,404 表示网页/网址不存在,在您发布的第一个代码中,您一直试图访问错误的 API,这就是您收到 404 https://en.wikipedia.org/wiki/HTTP_404
正确的 api - https://api.openweathermap.org/data/2.5/weather?
您试图访问的内容 - https://api.openweathermap.org/data/2.5/data/2.5/weather?
在改造 baseurl 中应该只有基本示例 - https://api.openweathermap.org/
端点应该在接口api调用@GET("data/2.5/weather?")中提供
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。