Получаю null с сервера
Использую Retrofit, чтобы получить данные о погоде с сервера. Но в responce.body() выводится null. Подскажите, где ошибка
Класс NetworkRequest
private static NetworkRequest request;
private static final String BASE_URL = "http://api.openweathermap.org/data/2.5/";
private Retrofit retrofit;
NetworkRequest() {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
public static NetworkRequest getRequest(){
if(request == null){
request = new NetworkRequest();
}
return request;
}
public WeatherAPI getWeatherApi(){
return retrofit.create(WeatherAPI.class);
}
}
Интерфейс WeatherAPI
public interface WeatherAPI {
@GET (""weather?q=Makhachkala&units=metric&APPID=0b08836a21c5d5280dbc3e634a3712a7"")
Call<List<Weather>> getWeather();
}
Класс-модель Weather
public class Weather {
@SerializedName("name")
@Expose
private String locale = "Город";
@SerializedName("temp")
@Expose
private String temperature = "Температура";
@SerializedName("description")
@Expose
private String description = "Статус";
@SerializedName("humidity")
@Expose
private String humidity = "Влажность";
public String getLocale() {
return locale;
}
public void setLocale(String locale) {
this.locale = locale;
}
public String getTemperature() {
return temperature;
}
public void setTemperature(String temperature) {
this.temperature = temperature;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getHumidity() {
return humidity;
}
public void setHumidity(String humidity) {
this.humidity = humidity;
}
}
MainActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView tvLocation = findViewById(R.id.tv_location);
final TextView tvTemperature = findViewById(R.id.tv_temperature);
final TextView tvDescription = findViewById(R.id.tv_description);
final TextView tvHumidity = findViewById(R.id.tv_humidity);
NetworkRequest.getRequest()
.getWeatherApi()
.getWeather()
.enqueue(new Callback<List<Weather>>() {
@Override
public void onResponse(Call<List<Weather>> call, Response<List<Weather>> response) {
System.out.println("вывелось - " + response.body());
}
@Override
public void onFailure(Call<List<Weather>> call, Throwable t) {
}
});
}
}
Ответы (2 шт):
Проблема в том, что ты дергаешь
https://api.openweathermap.org/data/2.5/weather?id=532096
а не
http://api.openweathermap.org/data/2.5/weather?q=Makhachkala&units=metric&APPID=0b08836a21c5d5280dbc3e634a3712a7
и получаешь ответ
{"cod":401, "message": "Invalid API key. Please see http://openweathermap.org/faq#error401 for more info."}
который не биндится в твою модель
Ну судя по тому что отдает этот запрос на api.openweathermap.org вы просто неверно построили модель. Я запустил их тестовый пример по вашему запросы и там приходит вот такой ответ:
{
"coord": {
"lon": 145.77,
"lat": -16.92
},
"weather": [
{
"id": 802,
"main": "Clouds",
"description": "scattered clouds",
"icon": "03n"
}
],
"base": "stations",
"main": {
"temp": 300.15,
"pressure": 1007,
"humidity": 74,
"temp_min": 300.15,
"temp_max": 300.15
},
"visibility": 10000,
"wind": {
"speed": 3.6,
"deg": 160
},
"clouds": {
"all": 40
},
"dt": 1485790200,
"sys": {
"type": 1,
"id": 8166,
"message": 0.2064,
"country": "AU",
"sunrise": 1485720272,
"sunset": 1485766550
},
"id": 2172797,
"name": "Cairns",
"cod": 200
}
А он не соответствует вашему объекту Weather.
Я вам рекомендую скачать для Android Studio плагин Robo POGO Generator или же воспользоваться каким-нибудь онлайн сервисом, например этим.
P.S. Как правильно заметил Circassian вам так же необходимо поменять протокол в вашей ссылке с https:// на http://