我正在为REST服务构建客户端。该服务具有一个生成令牌的登录服务。
登录服务具有以下格式:
$.post('http://xxx.xxx.xxx.xxx/?json=true',{machineID: "fMUVxYdG1X3hWb7GNkTd", mail: "user@user.com", pass: "123", function: "dash"},function(d){
console.log(d.$user)
})
具有以下响应。 auth_token是此服务中的apiKey。
{"ok":true,"auth_token":"078c302cecc90206fec20bc8306a93ba"}
因此,在我的Android应用中,我创建了一个类似
的界面public interface RestService {
@POST("/")
Call<LoginResponse> login(@Query("json") boolean json, @Body Login login);
@GET("/{apiKey}/monitor/{groupKey}")
Call<List<Monitor>> getMonitors(@Path("apiKey") String apiKey, @Path("groupKey") String groupKey);
@GET("/{apiKey}/monitor/{groupKey}/{monitorId}")
Call<Monitor> getMonitor(@Path("apiKey") String apiKey, @Path("groupKey") String groupKey, @Path("monitorId") String monitorId);
@GET("/{apiKey}/videos/{groupKey}/{monitorId}")
Call<VideoObject> getMonitorVideos(@Path("apiKey") String apiKey, @Path("groupKey") String groupKey, @Path("monitorId") String monitorId);
@GET("/{apiKey}/videos/{groupKey}")
Call<VideoObject> getVideos(@Path("apiKey") String apiKey, @Path("groupKey") String groupKey, @QueryMap Map<String, String> options);
@GET("/{apiKey}/control/{groupKey}/{monitorId}/{action}")
Call<ResponseBody> control(@Path("apiKey") String apiKey, @Path("groupKey") String groupKey, @Path("monitorId") String monitorId, @Path("action") String action);
}
我还有另一个启动服务的类。
public void init(String host, int port, boolean ssl) {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
baseUrl = String.format(Locale.getDefault(), "%s://%s:%d", (ssl ? HTTPS : HTTP), host, port);
okHttpClient = new OkHttpClient().newBuilder().addInterceptor(new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
return chain.proceed(originalRequest);
}
})
.addInterceptor(logging)
.build();
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(JacksonConverterFactory.create(mapper))
.client(okHttpClient)
.build();
restService = retrofit.create(RestService.class);
this.host = host;
this.port = port;
this.ssl = ssl;
}
这是登录服务和另一项服务。
public void login(final Login login, final Callback<LoginResponse> callback) {
Call<LoginResponse> call = restService.login(true, login);
call.enqueue(callback);
}
public void getMonitors(Callback<List<Monitor>> callback) {
Call<List<Monitor>> call = restService.getMonitors(apiKey, groupKey);
call.enqueue(callback);
}
但是,我希望能够在其他每个服务上调用登录服务,并且在成功响应后,我将调用实际的服务。
无论如何我都可以通过改装来做到这一点?
感谢任何反馈。