在我的android应用中,我像这样使用Retrofit:
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.POST;
public interface TangoRestClient {
@POST("/myproject/1/user/login")
Call<JsonElement> login(@Body JsonElement body);
@POST("/myproject/1/user/register")
Call<JsonElement> register(@Body JsonElement body);
@POST("/myproject/1/user/dictionary")
Call<JsonElement> getDictionary(@Body JsonElement body);
}
您会看到所有方法都具有相同的url前缀:
/myproject/1/user
可以提取此常量并像这样进行smt:
String prefix = " /myproject/1/user";
@POST("{prefix}/login")
Call<JsonElement> login(@Body JsonElement body);
@POST("{prefix}/register")
Call<JsonElement> register(@Body JsonElement body);
@POST("{prefix}/dictionary")
Call<JsonElement> getDictionary(@Body JsonElement body);
答案 0 :(得分:0)
我这样做的方法是创建一个interface
和一个管理类,它看起来像这样:
public class CatalogManager extends NetworkingManager {
private String id;
public CatalogManager(String baseUrl) {
super(baseUrl);
}
public CatalogManager(String baseUrl, String id) {
super(baseUrl);
this.id = id;
}
public interface CatalogInterface {
@GET("endpoint1")
Call<Data> getCatalogGenres();
@GET("endpoint2")
Call<Data> getGenreMovies(@Query("query_param") String id);
}
public void getCatalog(CatalogCallback callback){
CatalogInterface ci = retrofit.create(CatalogInterface.class);
Call call = ci.getEndpoint1();
call.enqueue(callback);
}
public void getCatalogCatagories(CatalogGenreCallback callback){
CatalogInterface ci = retrofit.create(CatalogInterface.class);
Call call = ci.getEndpoint2(id);
call.enqueue(callback);
}
@Override
protected OkHttpClient getHttpClient() {
return super.getHttpClient();
}
@Override
protected Gson getGson() {
return super.getGson();
}
}
然后,当我调用该方法时,就会执行:
CatalogManager cm = new CatalogManager(Constants.BASE_URL , getId());
cm.getEndpoint1(new CatalogGenreCallback() {
@Override
public void onResponse(Call<Data> call, Response<SliderData> response) {
Data data = response.body();
if (data != null) {
adapter.updateAdapterInfo(data);
}
}
@Override
public void onFailure(Call<Data> call, Throwable t) {
Log.e(TAG, "Error: " + t.toString());
}
});
在我有Constant.BASE_URL
的地方,您可以输入所需的任何URL。在您的情况下,您可以创建一个常量,该常量包含您的基数和通用路径:
CatalogManager cm = new CatalogManager(Constant.BASE_URL + Constant.COMMONT_PATH , getId());