我是android和REST客户端的新手。我正在使用改造来构建一个与API通信的应用程序。
许多教程说最佳实践是为每个接口声明1个方法(这么多方法意味着很多接口)。
示例:如果我想要2个方法,一个GET和一个POST。我需要两个接口:
public interface GetService {
@GET("/abc/xyz")
Call <ABC> getService();
}
public interface PostService {
@POST("/abc/def")
Call<XYZ> postServer(@Body XYZ content);
}
在main_activity中我需要调用
//call get
GetService get = ServiceGenerator.createService(GetService.class);
ABC call1 = get.getService();
//call post
PostService post = ServiceGenerator.createService(PostService.class);
XYZ call2 = post.postService();
为什么我不能只有这样一个界面:
public interface APIInterface {
@GET("/abc/xyz")
Call <ABC> getService();
@POST("/abc/def")
Call<XYZ> postServer(@Body XYZ content);
}
在Main_Activity中,我只需要执行以下操作:
APIInterface api = ServiceGenerator.createService(APIInterface.class);
ABC call1 = api.getService();
XYZ call2 = api.postServer();
答案 0 :(得分:2)
您不必遵循这种“良好做法”,每个界面只有一个服务。如果您按照下面的业务部分使用一个界面,则可以。
public interface ProductRestService {
@GET("/product/****")
Call <Product> getProduct(long id);
@PUT("/product/****")
Call <Product> update(long id, @Body Product product);
@POST("/product/****")
Call <Product> create(@Body Product product);
@DELETE("/product/****")
Call <Void> deleteProduct(long id);
}
目标只是避免使用所有应用服务的界面
答案 1 :(得分:0)
将所有内容放在一个界面中。您可以随时随地拨打电话。如果你有不同的Base Url,那么你可以有不同的界面。取决于开发人员
public interface RestApi {
@FormUrlEncoded
@POST("Token")
Observable<TokenResponse> normalLogin(
@Field("grant_type") String grant_type,
@Field("UserName") String UserName,
@Field("Password") String Password
);
@FormUrlEncoded
@POST("Account/VerifyExternalLogin")
Observable<ExternalLoginResponse> externalLogin(
@QueryMap HashMap<String,String> option
);
@FormUrlEncoded
@POST("Account/ResetPassword")
Observable<ResetResponse> requestPassword(
@Field("Email") String email
);
@GET("Profile")
Observable<UserDetail> getProfile();
@GET("History/{cartId}")
Observable<OrderHistoryResponse> getHistoryDetail(
@Path("cartId") int cartId
);
}