Retrofit2简单使用

版权声明:本文为博主原创文章,未经博主允许不得转载: https://mp.csdn.net/postedit/83142243

今天去看了一波 Retrofit2+RxJava2+MVP  网络请求模式,说实在的看得头都大了,还好网上大神多一点点学习下,我一次性也写不出那么高级的代码,只能一点点来, 先来一把 Retrofit2 请求网络数据吧, 后面的会补上,哎,这个还是要看理解能力

https://api.douban.com/v2/book/search?q=%E9%87%91%E7%93%B6%E6%A2%85&tag=&start=0&count=1

这是需要请求的json数据

我还需要的工具

implementation 'com.squareup.retrofit2:retrofit:2.1.0'
implementation 'com.squareup.retrofit2:converter-gson:2.1.0'

插件  GsonFormat

直接上吧。

1.GsonFormat  创建JavaBean类 我这创建的是BookBean     代码就不贴了,反正都是自动生成的

GsonFormat 插件使用方式 :https://blog.csdn.net/qq_32368129/article/details/53378513

2.创建请求接口 RetrofitSerVice 我这用的是GET 注解  问我为什么,因为简单

public interface RetrofitSerVice {


    //https://api.douban.com/v2/book/search?q=%E9%87%91%E7%93%B6%E6%A2%85&tag=&start=0&count=1
    //https://api.douban.com/v2/book/search
    @GET("book/search")
    Call<BookBean> getSearchBook(@Query("q") String name,
                                 @Query("tag") String tag,
                                 @Query("start") int start,
                                 @Query("count") int count);

}

什么是注解,看一些大佬:https://blog.csdn.net/qiang_xi/article/details/53959437

3.使用网络接口,请求数据  重点来了!!

private void net() {
    Log.e("tags","net");
    Retrofit retrofit=new Retrofit.Builder()
            .baseUrl("https://api.douban.com/v2/")
            .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().create()))
            .build();

    RetrofitSerVice serVice=retrofit.create(RetrofitSerVice.class);
    Call<BookBean> call =serVice.getSearchBook("金瓶梅",null,0,1);
    call.enqueue(new Callback<BookBean>() {

        @Override
        public void onResponse(Call<BookBean> call, Response<BookBean> response) {
            final List<BookBean.BooksBean> books = response.body().getBooks();

            for (int i=0;i<books.size();i++){
                Log.e("tags","数据: "+books.get(i).toString());
                final int finalI = i;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mTextView.setText(books.get(finalI).toString());
                    }
                });
            }
        }

        @Override
        public void onFailure(Call<BookBean> call, Throwable t) {
            Log.e("tags","网络请求失败");
        }
    });
}

核心就在这里面,只讲主要的几个方法

1.创建Retrofit .Builder ()

.baseUrl("https://api.douban.com/v2/")    拼凑出你网络数据的完整地址

.addConverterFactory(GsonConverterFactory.create(new GsonBuilder().create()))  使用Gson 解析

Call<BookBean> call =serVice.getSearchBook("金瓶梅",null,0,1); 创建Call 回调,不使用RxJava

call.enqueue(new Callback<BookBean>() {xxxx}  异步请求数据  接口返回2个方法 

onResponse()成功   会携带Response<BookBean> response     数据体

onFailure() 失败

点击后

单独使用 Retrofit   还是很简单的,  当然要封装, 或者加上RxJava、RxAndroid 、MVP 等其他七七八八的模式一起使用就会觉得头晕了,这些我也会慢慢加上去、到时候再记录学习!

猜你喜欢

转载自blog.csdn.net/qq_32425789/article/details/83142243