我最近在 Retrofit 1.9 旁边实现了 Retrofit 2.9.0,因为版本 2 处理会话的能力要好得多,而且我的一个 API 调用由于缺少处理响应 cookie(会话)而失败。
我有同样的问题,此时将整个项目迁移到 Retrofit 2 是不可行的。不过我可以确认它正在工作。
我将向您展示我是如何实现 1.9 和 2.9.0 的。完整课程的链接见底部。
对于两者:
创建一个类,您可以从中访问您的 Retrofit 对象并调用接口:
public class ApiManager {
private static final String TAG = "API MANAGER";
private static final String API_URL = BuildConfig.API_URL;
private static Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
.setLenient()
.create();
// The rest of the class to follow
然后具体到 1.9:
private static RequestInterceptor requestInterceptor = new RequestInterceptor() {
@Override
public void intercept(RequestInterceptor.RequestFacade request) {
SessionManager sessionManager = new SessionManager(ContextHandler.getContext());
HashMap session = sessionManager.getUserDetails();
Object session_id = session.get("session_id");
Object token = session.get("token");
if (session_id != null && token != null) {
request.addHeader("Cookie", "session_id=" + session_id + ";");
request.addHeader("Cookie", "token=" + token + ";");
Log.i("INTERCEPT", "Sent Cookies");
}
request.addHeader("Accept", "application/json");
}
};
public static OkHttpClient getClient() {
// init okhttp 3 logger
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
JavaNetCookieJar jncj = new JavaNetCookieJar(CookieHandler.getDefault());
OkHttpClient client = new OkHttpClient();
client.newBuilder()
.addInterceptor(new AddCookiesInterceptor(ContextHandler.getContext()))
.addInterceptor(new ReceivedCookiesInterceptor(ContextHandler.getContext()))
.addNetworkInterceptor(logging)
.cookieJar(jncj)
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.MINUTES);
return client;
}
private static final RestAdapter REST_ADAPTER = new RestAdapter.Builder()
.setEndpoint(API_URL) // On device
.setRequestInterceptor(requestInterceptor)
.setClient(new Ok3Client(getClient()))
.setConverter(new GsonConverter(gson))
.setLogLevel(RestAdapter.LogLevel.FULL) //log the request
.build();
public interface AuthenticationInterface {
@Headers("Content-type: application/json")
@POST("/auth/getsession")
void Authenticate(@Body Authentication Auth, Callback<SessionStore> response);
@Headers("Content-type: application/json")
@GET("/auth/logout")
void logout(Callback<String> response);
@Headers("Content-type: application/json")
@GET("/auth/logout")
String logout();
}
// Bind REST_ADAPTER to Interface
public static final AuthenticationInterface AUTHENTICATION_INTERFACE = REST_ADAPTER.create(AuthenticationInterface.class);
// Use this when you want to run the request.
public static AuthenticationInterface getAuthenticationService(){ return AUTHENTICATION_INTERFACE; }
所以你会使用上面的如下:
ApiManager.getAuthenticationService().Authenticate(auth, new Callback<SessionStore>() {
@Override
public void success(SessionStore sessionStore, Response response) {
// Do somthing
}
@Override
public void failure(RetrofitError error) {
// Handle Error
}
});
对于 2.9.0:
public static OkHttpClient getHeader() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient okClient = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.addInterceptor(new AddCookiesInterceptor(ContextHandler.getContext()))
.addInterceptor(new ReceivedCookiesInterceptor(ContextHandler.getContext()))
.cookieJar(cookieJar)
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.MINUTES)
.addNetworkInterceptor(
new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request request = null;
Log.d("--Authorization-- ", "authorizationValue");
Request original = chain.request();
// Request customization: add request headers
Request.Builder requestBuilder = original.newBuilder();
SessionManager sessionManager = new SessionManager(ContextHandler.getContext());
HashMap session = sessionManager.getUserDetails();
Object session_id = session.get("session_id");
Object token = session.get("token");
if (session_id != null && token != null) {
requestBuilder.addHeader("Cookie", "session_id=" + session_id + ";");
requestBuilder.addHeader("Cookie", "token=" + token + ";");
Log.i("INTERCEPT", "Sent Cookies");
}
requestBuilder.addHeader("Accept", "application/json");
request = requestBuilder.build();
return chain.proceed(request);
}
})
.build();
return okClient;
}
private static final Retrofit REST_ADAPTER2 = new Retrofit.Builder()
.baseUrl(API_URL) // On device
.client(getHeader())
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
public interface JasperReportsInterface {
/**
*
* @param agent_id
* @param report_id
*/
@retrofit2.http.Headers("Content-type: application/json")
@retrofit2.http.GET("/agents/{agent_id}/reports/{report_id}/")
Call<Reports> GetAgentReportView(@retrofit2.http.Path("agent_id") String agent_id, @retrofit2.http.Path("report_id") String report_id);
/**
*
* @param agent_id
* @param report_id
*/
@retrofit2.http.Headers("Content-type: application/json")
@retrofit2.http.GET("/agents/{agent_id}/reports/{report_id}/jobs")
Call<Jobs> PollAgentReportData(@retrofit2.http.Path("agent_id") String agent_id, @retrofit2.http.Path("report_id") String report_id);
/**
*
* @param agent_id
* @param report_id
* @param jsonBody
*/
@retrofit2.http.Headers("Content-type: application/json")
@retrofit2.http.POST("/agents/{agent_id}/reports/{report_id}/jobs")
Call<String> PostAgentReportData(@retrofit2.http.Path("agent_id") String agent_id, @retrofit2.http.Path("report_id") String report_id, @retrofit2.http.Body JsonObject jsonBody);
/**
*
* @param agent_id
* @param report_id
* @param jsonBody
*/
@retrofit2.http.Headers("Content-type: application/json")
@retrofit2.http.POST("/agents/{agent_id}/reports/{report_id}/jobs")
Call<String> DownloadAgentReportData(@retrofit2.http.Path("agent_id") String agent_id, @retrofit2.http.Path("report_id") String report_id, @retrofit2.http.Body JsonObject jsonBody);
}
// Bind REST_ADAPTER2 to Interface
public static final JasperReportsInterface JASPER_REPORTS_INTERFACE = REST_ADAPTER2.create(JasperReportsInterface.class);
// Use this when you want to run the request.
public static JasperReportsInterface getJasperReportsService(){ return JASPER_REPORTS_INTERFACE; }
您可以按以下方式使用上述内容:
Call<Reports> reportsCall = ApiManager.getJasperReportsService().GetAgentReportView(agentsID, reportTypeID);
reportsCall.enqueue(new retrofit2.Callback<Reports>() {
@Override
public void onResponse(Call<Reports> call, retrofit2.Response<Reports> response) {
if(response.isSuccessful()) {
report = response.body();
} else {
int statusCode = response.code();
// handle request errors yourself
ResponseBody errorBody = response.errorBody();
}
}
@Override
public void onFailure(Call<Reports> call, Throwable t) {
}
});
您需要的依赖项分别是 1.9 和 2 所需的基本依赖项。
请参阅here 了解完整课程。