首页 > 代码库 > 网络请求--Retrofit2用法

网络请求--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. 基本请求

使用接口, 区分GetPost方法.

/**
 * 网络请求
 * <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和password
 * <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.

<script type="text/javascript"> $(function () { $(‘pre.prettyprint code‘).each(function () { var lines = $(this).text().split(‘\n‘).length; var $numbering = $(‘
    ‘).addClass(‘pre-numbering‘).hide(); $(this).addClass(‘has-numbering‘).parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($(‘
  • ‘).text(i)); }; $numbering.fadeIn(1700); }); }); </script>

网络请求--Retrofit2用法