【发布时间】:2016-08-05 08:38:43
【问题描述】:
我正在使用 wunderground API 制作天气应用程序。我也在使用 Retrofit2 和 GSON 库。
这是获取 JSON 响应的 API URL 格式:
http://api.wunderground.com/api/API_KEY/conditions/q/ISO_COUNTRY_CODE/CITY_NAME.json
我已经声明了一个 java API_Interface 如下:
public interface API_Interface {
@GET("/api/{apikey}/conditions/q/BD/{city}.json")
Call<CurrentObservation> getCurrentWeather(
@Path("apikey") String apikey,
@Path("city") String city);
}
并尝试从MainActivity 传递apikey 和city,如下所示:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
API_Interface weatherService = retrofit.create(API_Interface.class);
Call<CurrentObservation> call = weatherService.getCurrentWeather(Constants.API_KEY,"Dhaka");
call.enqueue(new Callback<CurrentObservation>() {
@Override
public void onResponse(Call<CurrentObservation> call, Response<CurrentObservation> response) {
textView.setText(response.body().toString());
Log.d("result",response.body().toString());
}
@Override
public void onFailure(Call<CurrentObservation> call, Throwable t) {
textView.setText("Something went wrong: " + t.getMessage());
Log.e("error",t.getMessage());
}
});
这是Constant 类:
public class Constants {
public static final String BASE_URL="http://api.wunderground.com";
public static final String API_KEY="b5efba6dc63cc1b1";
}
这是CurrentObservation类的POJO模型:http://paste.ubuntu.com/22291964/
我已经覆盖了模型中的 toString() 方法。
还有一些其他的 POJO 类-
但是这种方法给出了如下的空响应-
Weather Status: null
Pressure: null
Humidity: null
Temperature: null
这是来自 API URL 的实际 JSON 响应 - http://paste.ubuntu.com/22292683/
如何将参数传递给@GET 以获得正确的响应?
【问题讨论】:
-
这是正确的。你确定
Constants.API_KEY是正确的吗?响应的 HTTP 代码是什么? -
添加了更多详细信息。请立即查看。
标签: java android json gson retrofit