我从API接收数据时遇到问题。我收到的代码是200。响应为空。
public void makeRetrofitCall(){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://openweathermap.org/data/2.5/")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiCalls api = retrofit.create(ApiCalls.class);
Call<Model.Main> call = api.getNewestForecast(latitude,longitude,APP_ID);
call.enqueue(new Callback<Model.Main>() {
@Override
public void onResponse(Call<Model.Main> call, Response<Model.Main> response) {
if (!response.isSuccessful()){
Log.i(TAG, "AWS: "+response.code());
}
Log.i(TAG, "onResponse: "+response.code());
List<Model.Main> list = Collections.singletonList(response.body());
for (Model.Main main : list){
String content = "";
content += main.getTemperature();
Log.i(TAG, "onResponse : \n"+content);
}
}
@Override
public void onFailure(Call<Model.Main> call, Throwable t) {
Log.i(TAG, "onFailure: "+t.getMessage());
}
});
}
}
Api
@GET("weather")
Call<Model.Main> getNewestForecast(
@Query("lat") Double latitude,
@Query("lon") Double longitude,
@Query("appid") String key);
POJO
public class Model {
@SerializedName("main")
private Main main;
public Main getMain() {
return main;
}
class Main {
@SerializedName("temp")
private Double actualTemperature;
public Double getTemperature() {
return actualTemperature;
}
}
}
编辑,忘记添加回复。 JSON响应
{
"coord": {
"lon": -0.12,
"lat": 51.51
},
"weather": [
{
"id": 500,
"main": "Rain",
"description": "light rain",
"icon": "10d"
}
],
"base": "stations",
"main": {
"temp": 20.07,
"pressure": 1013,
"humidity": 64,
"temp_min": 17.22,
"temp_max": 23
},
"visibility": 10000,
"wind": {
"speed": 4.1,
"deg": 350
},
"clouds": {
"all": 75
},
"dt": 1562435414,
"sys": {
"type": 1,
"id": 1414,
"message": 0.0123,
"country": "GB",
"sunrise": 1562385062,
"sunset": 1562444336
},
"timezone": 3600,
"id": 2643743,
"name": "London",
"cod": 200
}
纬度和经度正确,api_key也正确。我认为pojo课堂有些特色。我应该在代码中进行哪些更改才能使其正常工作?
答案 0 :(得分:1)
我认为您的错误正在添加您的模型 将您的api响应从Model.Main更改为Main
更改代码
更改
@GET("weather")
Call<Model.Main> getNewestForecast(
@Query("lat") Double latitude,
@Query("lon") Double longitude,
@Query("appid") String key);
收件人
@GET("weather")
Call<Model> getNewestForecast(
@Query("lat") Double latitude,
@Query("lon") Double longitude,
@Query("appid") String key);