Yon*_* Jo 2 android json network-programming retrofit2
Retrofit retrofit = new Retrofit.Builder().baseUrl(Api.Q_BASE)
.addConverterFactory(GsonConverterFactory.create()).client(client).build();
Api.ApiInter inter = retrofit.create(Api.ApiInter.class);
Call<JSONObject> call = inter.getMovieData(sortType[0], Api.P_KEY);
call.enqueue(new Callback<JSONObject>() {
@Override
public void onResponse(Call<JSONObject> call, Response<JSONObject> response) {
/* */
}
@Override
public void onFailure(Call<JSONObject> call, Throwable t) {
Log.d(LOG_TAG, "failed to get response.");
}
});
Run Code Online (Sandbox Code Playgroud)
/
public class Api {
public static final String Q_BASE = "http://api.themoviedb.org/";
public static final String Q_KEY = "api_key";
public static final String Q_RESULT = "results";
public static final String Q_POSTER_PATH = "poster_path";
public static final String Q_TITLE = "title";
public static final String Q_OVERVIEW = "overview";
public static final String Q_DATE = "release_date";
public static final String Q_VOTE_AVERAGE = "vote_average";
public static final String P_KEY = "This is private key";
public static final String REQUEST = "GET";
public static final String I_BASE = "http://image.tmdb.org/";
public static final String P_POSTER_SIZE = "w185";
public interface ApiInter {
@GET("3/movie/{sort}")
Call<JSONObject> getMovieData(@Path("sort") String sort, @Query("api_key") String key);
@GET("t/p/{size}/{url}")
Call<Bitmap> getMoviePoster(@Path("size") String size, @Path("url") String url);
}
}
Run Code Online (Sandbox Code Playgroud)
[![调试器]](https://i.stack.imgur.com/Tasfl.jpg)
当我调试我的应用程序时,response.body()始终仅重新启动"{}".如果我更改了Call的元素,则返回值将为null.我不知道原因.我想获得JSON数据.我怎么解决这个问题?我可以设置okhttp客户端吗?或更改Call的返回类型?请给我答案.
这是一个非常简单的错误.如果你有像我这样的问题,请检查这三件事.
你的api接口方法返回 Call<JSONObjcet>
请求成功,但response.body()只是"{}"
改造使用GsonConverter.所以我们需要在包中使用jsonObject com.google.gson.你必须JSONObject改为JsonObject