我如何在改造网络呼叫中使用这些查询并将其显示在类别结果
中https://api.themoviedb.org/3/genre/{genre_id}/movies
答案 0 :(得分:2)
也许这可能会有所帮助:
接口类
public interface TheApiInterface{
@GET("url/bits/until/{path_variable}/then/more/url")
Call<TheThingResponse> getTheThing(@Path("path_variable") String var);
}
活动或其他:
public class ThePlaceYoureCallingItFrom {
//set up the api interface and http client
public TheApiInterface getApi(){
String endpoint = "https://api.root.site/api/";
//set up retrofit object
return new Retrofit.Builder().baseUrl(endpoint)
//add chosen converter factory for pojo serialization
.addConverterFactory(GsonConverterFactory.create())
//add the OKHTTP client
.client(new OkHttpClient.Builder().build())
//now gimme
.build().create(TheApiInterface.class);
}
public void callGetTheThing(){
//create call
Call<TheThingResponse> call = getApi().getTheThing("somePathVar");
//set callback
ThingResponseCallback callback = new ThingResponseCallback(this, THING_RESPONSE_INTENT_FILTER);
//fire
call.enqueue(callback);
}
}
回调:
public class ThingResponseCallback implements Callback<TheThingResponse>{
@Override
public void onResponse(Call<TheThingResponse> call, Response<TheThingResponse> response) {
if (response.isSuccessful() && response.body() != null) {
Log.i(TAG, "onResponse: success: theResponseFieldIWant1: " + response.theResponseFieldIWant1;);
} else {
Log.i(TAG, "onResponse: something went wrong with the response object " +response.body());
}
}
@Override
public void onFailure(Call<TheThingResponse> call, Throwable t) {
Log.i(TAG, "onFailure: to: " + call.request().url() + " req " + call.request());
}
}
响应pojo:
public class TheThingResponse{
@SerializedName("theJsonKeyOfTheFieldReturnedInServerResponse1")
public String theResponseFieldIWant1;
@SerializedName("theJsonKeyOfTheFieldReturnedInServerResponse2")
public String theResponseFieldIWant2;
@SerializedName("theJsonKeyOfTheFieldReturnedInServerResponse3")
public String theResponseFieldIWant3;
@SerializedName("theJsonKeyOfTheFieldReturnedInServerResponse4")
public String theResponseFieldIWant4;
}
您收到的JSON将如下所示:
{
"theJsonKeyOfTheFieldReturnedInServerResponse1": "the value I wanted 1",
"theJsonKeyOfTheFieldReturnedInServerResponse2": "the value I wanted 2",
"theJsonKeyOfTheFieldReturnedInServerResponse3": "the value I wanted 3",
"theJsonKeyOfTheFieldReturnedInServerResponse4": "the value I wanted 4"
}
但您可以为更复杂的JSON构建更复杂的POJO。
我发现让我的POJO共享一个Serializable父类很有用,可以让它们在Callback中轻松移动,但你也可以在这里很容易地使用ContentProvider并将一些行插入数据库或如果你想要一个更永久的存储,那就是这样的。
但请记住这都是异步 - 如果你想要同步的Retrofit调用,你可以使用call.execute()