android retrofit2的基本使用,搭配rxjava

依赖

implementation 'com.google.code.gson:gson:2.6.1'
implementation 'com.orhanobut:logger:2.1.0'
implementation 'com.squareup.okhttp3:okhttp:3.11.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'
implementation 'io.reactivex.rxjava2:rxjava:2.2.3'
implementation 'com.squareup.retrofit2:adapter-rxjava:2.4.0'
implementation 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'

最简单的使用:

先创建接口:

public interface WeatherService {

    @GET("s6/weather/now")
    Observable<WeatherEntity> getWeather(@Query("key") String key, @Query("location") String location);

    @GET("/")
    Call<ResponseBody> baidu();
}

两个get

使用异步获取返回的原生字符串

OkHttpClient client = new OkHttpClient.Builder().
        connectTimeout(1, TimeUnit.SECONDS).
        readTimeout(60, TimeUnit.SECONDS).
        writeTimeout(60, TimeUnit.SECONDS).build();
Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://badu.com")
        .client(client)
        .addConverterFactory(GsonConverterFactory.create())
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .build();

Call<ResponseBody> stringvalue = retrofit.create(WeatherService.class).baidu();
stringvalue.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
        //访问成功时调用,调用方法是response.body.string()
        try {
            Log.d(TAG, "onResponse: "+response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFailure(Call<ResponseBody> call, Throwable t) {
        //如果访问失败的调用
        Log.d(TAG, "onFailure: "+"失败了");
    }
});

使用rxjava

//创建一个连接对象,设置连接超时时间,读超时时间,写超时
OkHttpClient.Builder client = new OkHttpClient.Builder().
        connectTimeout(1, TimeUnit.SECONDS).
        readTimeout(60, TimeUnit.SECONDS).
        writeTimeout(60, TimeUnit.SECONDS);
Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://free-api.heweather.com")
        .client(client.build())
        .addConverterFactory(GsonConverterFactory.create())
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .build();
WeatherService weatherService = retrofit.create(WeatherService.class);
weatherService.getWeather("xxxxx", "郑州")
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Observer<WeatherEntity>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(WeatherEntity weatherEntity) {
                //响应解析的序列一个个进来
                weatherEntities.add(weatherEntity);
            }

            @Override
            public void onError(Throwable e) {
                //出错了时候
                mView.dataError(e);
            }

            @Override
            public void onComplete() {
                //响应解析的所有东西都完成了调用
                mView.setData(weatherEntities);
            }
        });


打印log

HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor();
if(BuildConfig.DEBUG){
    //显示日志
    logInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
}else {
    logInterceptor.setLevel(HttpLoggingInterceptor.Level.NONE);
}
client.addInterceptor(logInterceptor);

让一个okhttp.builder对象client添加以下这个log解析器就ok

自定义结果解析器

自己解析返回的结果GsonConverFactory.create,点进去这个方法,主要看responseBodyConverter方法,这个是处理返回请求的,他是调用了GsonResponseBodyConverter来处理请求,点进去这个类,public T convert(ResponseBody value)这个方法就是返回要构造的对象,参数value就是返回的response的body值,可以通过value.string();得到具体的字符串,在这个方法里解析可以通过throw的方式调用观察者的onError方法


所以重写结果解析器需要复制出来GsonConverFactory这个类,并且复制GsonResponseBodyConverter和GsonRequestBodyConverter这两个类,并且重新写一下GsonResponseBodyConverter这个类的convert方法对结果进行解析

@Override
public T convert(ResponseBody value) throws IOException {
    String response = value.string();
    Log.d("tag", "convert: " + response);
    //抛出异常,通过观察者的onError回掉接收结果
    if (1 == 1)
        throw new JsonIOException("抛出异常");
    JsonReader jsonReader = gson.newJsonReader(value.charStream());
    try {
        T result = adapter.read(jsonReader);
        if (jsonReader.peek() != JsonToken.END_DOCUMENT) {
            throw new JsonIOException("JSON document was not fully consumed.");
        }
        return result;
    } finally {
        value.close();
    }
}


xwm

还是一个菜鸟


Comments are closed.