[英]Retrofit2 MVP Android
我在我的项目上使用翻新,并且想知道是否有一种方法可以将对不同类的api的调用分开,例如:仅登录活动/ api / users / login电影活动仅/ api / movies /我拥有的所有活动都在相同的界面上,我发现这不是一个好方法...请您指导我如何使其变得更整洁? 我正在使用MVP架构进行清理。
这是我的NetworkService.class
public class NetworkService {
private NetworkAPI networkAPI;
private OkHttpClient okHttpClient;
private LruCache<Class<?>, Observable<?>> apiObservables;
public NetworkService() {
this(BASE_URL);
}
public NetworkService(String baseUrl) {
okHttpClient = buildClient();
apiObservables = new LruCache<>(10);
Gson gson = new GsonBuilder()
.setLenient()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
.create();
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
// set your desired log level
//logging.setLevel(Level.BASIC);
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
Builder httpClient = new Builder()
.connectTimeout(100, TimeUnit.SECONDS)
.readTimeout(100, TimeUnit.SECONDS);
httpClient.addInterceptor(logging);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create(gson))
.client(httpClient.build())
.build();
networkAPI = retrofit.create(NetworkAPI.class);
}
/**
* Method to return the API interface.
*
* @return
*/
public NetworkAPI getAPI() {
return networkAPI;
}
/**
* Method to build and return an OkHttpClient so we can set/get
* headers quickly and efficiently.
*
* @return
*/
public OkHttpClient buildClient() {
Builder builder = new Builder();
builder.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
// Do anything with response here
//if we want to grab a specific cookie or something..
return response;
}
});
builder.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
//this is where we will add whatever we want to our request headers.
Request request = chain.request().newBuilder().addHeader("Accept", "application/json").build();
return chain.proceed(request);
}
});
return builder.build();
}
/**
* Method to clear the entire cache of observables
*/
public void clearCache() {
apiObservables.evictAll();
}
}
我的NetworkAPI.class
有这个
public interface NetworkAPI {
@POST(LOGIN)
Call<LoginResponse> login(@Body LoginRequest loginRequest);
//And more calls...
}
你们知道我能做得更干净吗?
使retrofit
实例单例,然后您可以为登录电影创建服务,例如
LoginService login = retrofit.create(LoginService.class);
login.login(loginRequest)
MovieService movie = retrofit.create(MovieService.class);
movie.movies(movieRequest)
这是你的界面看起来像
public interface LoginService {
@POST(LOGIN)
Call<LoginResponse> login(@Body LoginRequest loginRequest);
//And more calls...
}
public interface MovieService {
@POST(MOVIE)
Call<MovieResponse> movies(@Body MovieRequest movieRequest);
//And more calls...
}
需要优化的一件事是,您应该重用OkHttpClient
而不是为每个API创建一个。
改造API的创建也应重构为实用程序类:
public class RetrofitFactory {
private static OkHttpClient baseClient = new Builder().addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
// Do anything with response here
//if we want to grab a specific cookie or something..
return response;
}
}).addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
//this is where we will add whatever we want to our request headers.
Request request = chain.request().newBuilder().addHeader("Accept", "application/json").build();
return chain.proceed(request);
}
}).build();
private static Gson gson = new GsonBuilder()
.setLenient()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
.create();
private static Retrofit.Builder baseRetrofitBuilder = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson));
public Builder baseClientBuilder() {
return baseClient.newBuilder();
}
public static <T> T createApi(String url, Class<T> apiClass) {
return baseRetrofitBuilder.baseUrl(url).build().create(apiClass);
}
public static <T> T createApi(String url, Class<T> apiClass, OkHttpClient client) {
return baseRetrofitBuilder.baseUrl(url).client(client).build().create(apiClass);
}
}
要使用其他拦截器创建NetworkAPI,您可以执行以下操作:
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
// set your desired log level
//logging.setLevel(Level.BASIC);
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient httpClient = RetrofitFactory.baseClientBuilder()
.connectTimeout(100, TimeUnit.SECONDS)
.readTimeout(100, TimeUnit.SECONDS)
.addInterceptor(logging);
networkApi = RetrofitFactory.createApi(url, NetworkApi.class, httpClient);
要使用默认设置创建XApi,请执行以下操作:
xApi = RetrofitFactory.createApi(url, XApi.class);
也许您可以创建不同的接口,并修改NetworkService来创建Retrofit适配器,具体取决于您要在不同情况下使用的接口。
让我告诉你这个主意:
接口:
public interface LoginInterface {
@POST(LOGIN)
Call<LoginResponse> login(@Body LoginRequest loginRequest);
}
public interface MovieInterface {
@GET(MOVIE)
Call<MovieResponse> getMovies();
}
NetworkService类别
在这里,您可以看到用于网络服务的Singleton和使用此方法创建的方法,您可以使用Singleton实例创建其他接口:
public class NetworkService {
private final String API_BASE_URL = "";
private static NetworkService INSTANCE = null;
private static Retrofit retrofit;
private OkHttpClient okHttpClient;
private LruCache<Class<?>, Observable<?>> apiObservables;
public NetworkService() {
createInstance();
}
public static NetworkService getInstance() {
if(INSTANCE == null){
return new NetworkService();
}
return INSTANCE;
}
private void createInstance(){
okHttpClient = buildClient();
apiObservables = new LruCache<>(10);
Gson gson = new GsonBuilder()
.setLenient()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
.create();
retrofit = new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.client(httpClient.build())
.build();
}
public static <T> T create(Class<T> apiClass) {
return retrofit.create(apiClass);
}
private OkHttpClient buildClient() {
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.addInterceptor(loggingInterceptor)
.connectTimeout(100, TimeUnit.SECONDS)
.readTimeout(100, TimeUnit.SECONDS);
builder.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
// Do anything with response here
//if we want to grab a specific cookie or something..
return response;
}
});
builder.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
//this is where we will add whatever we want to our request headers.
Request request = chain.request().newBuilder().addHeader("Accept", "application/json").build();
return chain.proceed(request);
}
});
return builder.build();
}
/**
* Method to clear the entire cache of observables
*/
public void clearCache() {
apiObservables.evictAll();
}
}
然后,可以使用修改后的NetworService使用实例化它来实例化要使用的接口:
NetworService实例化:
public class LoginActiviy extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//Instantiation of LoginInterface
LoginInterface loginInterface =
NetworkService.getInstance().create(LoginInterface.class);
//Then we use the method for login
loginInterface.login(/* Handling the callback here*/);
}
}
public class MoviesActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movies);
//Instantiation of MovieInterface
MovieInterface movieInterface =
NetworkService.getInstance().create(MovieInterface.class);
//Then we use the method for login
loginInterface.getMovies(/* Handling the callback here*/);
}
}
我希望它可以帮助您获得更好的主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.