Android网络请求--Retrofit2使用方法
欢迎Follow我的 GitHub , 关注我的CSDN.
Retrofit 是Square开发的网络请求库, 简化了网络请求的使用, 这个库太知名了, 好处我就不多说了. 让我们看看如何使用吧?
注意: Retrofit2的beta3版本, 使用Okhttp3, Interceptor使用方式发生改变.
主要
(1) Retrofit2( beta3 )的请求方式.
(2) Okhttp3的Interceptor.
(3) Okhttp3的Deserializer.
(4) Retrofit2使用 Gson转换器(Converter) 和 RxJava适配器(Adapter) .
Github 下载地址
1. 基本请求
使用接口, 区分 Get 和 Post 方法.
/** * 网络请求 * <p> * Created by wangchenlong on 16/1/21. */ public interface MarvelService { String END_POINT = "http://gateway.marvel.com/"; String PARAM_API_KEY = "apikey"; String PARAM_HASH = "hash"; String PARAM_TIMESTAMP = "ts"; @GET("/v1/public/characters") Observable<List<AvengersCharacter>> getCharacters(@Query("offset") int offset); }
使用Retrofit类创建接口服务, 指定Gson为转换器, RxJava为适配器.
public class RestDataSource implements Repository { private final MarvelService mMarvelService; @Inject public RestDataSource() { // Log信息 HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC); // 公私密匙 MarvelSigningInterceptor signingInterceptor = new MarvelSigningInterceptor( BuildConfig.MARVEL_PUBLIC_KEY, BuildConfig.MARVEL_PRIVATE_KEY); // OkHttp3.0的使用方式 OkHttpClient client = new OkHttpClient.Builder() .addInterceptor(signingInterceptor) .addInterceptor(loggingInterceptor) .build(); // 选择人物信息 Gson customGsonInstance = new GsonBuilder() .registerTypeAdapter(new TypeToken<List<AvengersCharacter>>() { }.getType(), new MarvelResultsDeserializer<AvengersCharacter>()) .create(); // 适配器 Retrofit marvelApiAdapter = new Retrofit.Builder() .baseUrl(MarvelService.END_POINT) .addConverterFactory(GsonConverterFactory.create(customGsonInstance)) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .client(client) .build(); // 服务 mMarvelService = marvelApiAdapter.create(MarvelService.class); } // 返回人物信息 @Override public Observable<List<AvengersCharacter>> getCharacters(int currentOffset) { return mMarvelService.getCharacters(currentOffset); } }
2. Interceptor
Interceptor是拦截器, 在发送之前, 添加一些参数, 或者获取一些信息.如MarvelSigningInterceptor是添加参数, loggingInterceptor是打印参数.
/** * 添加Key和密码 * <p> * Created by wangchenlong on 16/1/21. */ public class MarvelSigningInterceptor implements Interceptor { private final String mApiKey; private final String mApiSecret; public MarvelSigningInterceptor(String apiKey, String apiSecret) { mApiKey = apiKey; mApiSecret = apiSecret; } @Override public Response intercept(Interceptor.Chain chain) throws IOException { String marvelHash = MarvelApiUtils.generateMarvelHash(mApiKey, mApiSecret); Request oldRequest = chain.request(); // 添加新的参数 HttpUrl.Builder authorizedUrlBuilder = oldRequest.url() .newBuilder() .scheme(oldRequest.url().scheme()) .host(oldRequest.url().host()) .addQueryParameter(MarvelService.PARAM_API_KEY, mApiKey) .addQueryParameter(MarvelService.PARAM_TIMESTAMP, MarvelApiUtils.getUnixTimeStamp()) .addQueryParameter(MarvelService.PARAM_HASH, marvelHash); // 新的请求 Request newRequest = oldRequest.newBuilder() .method(oldRequest.method(), oldRequest.body()) .url(authorizedUrlBuilder.build()) .build(); return chain.proceed(newRequest); } }
addQueryParameter添加网络参数.
Okhttp3使用了装饰者模式, 使用Builder添加Interceptor.
// OkHttp3.0的使用方式 OkHttpClient client = new OkHttpClient.Builder() .addInterceptor(signingInterceptor) .addInterceptor(loggingInterceptor) .build();
3. Deserializer
Deserializer是反序列化, Gson使用, 去除不使用的参数.
public class MarvelResultsDeserializer<T> implements JsonDeserializer<List<T>> { @Override public List<T> deserialize(JsonElement je, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { // 转换Json的数据, 获取内部有用的信息 JsonElement results = je.getAsJsonObject().get("data") .getAsJsonObject().get("results"); return new Gson().fromJson(results, typeOfT); } }
Gson使用Deserializer, 过滤不用的参数.
// 选择人物信息 Gson customGsonInstance = new GsonBuilder() .registerTypeAdapter(new TypeToken<List<AvengersCharacter>>() { }.getType(), new MarvelResultsDeserializer<AvengersCharacter>()) .create();
4. 获取数据
Rx选择执行线程和返回线程.
private void loadData() { mCharactersSubscription = mRepository.getCharacters(0) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(avengersCharacters -> { mMainView.setListData(avengersCharacters); }); }
Rxjava + Dagger + Retrofit , 三个编程库, 都已经写完了, 基本都是在一起使用. 文章里面都含有独立Demo, 大家可以配合使用, 感谢Square给我们带来, 的优雅代码.
OK, that’s all! Enjoy it.
</div>来自: http://blog.csdn.net/caroline_wendy/article/details/50557470