Android之Retrofit网络获取框架

Retrofit网络获取能优点很多,最实用的就是不用进行麻烦的Json具体解析,简单,优化,高效率

原理解析:https://blog.csdn.net/u011311586/article/details/79716863

一、创建接口:

public interface MenuService {
    //http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&page=1
    //通过Get注解,获取网络Jasn数据:
    @GET("dish_list.php?stage_id=1&limit=20&page=1")
    Call<JavaBean> getResualt();
}

二、创建javaBean类:

三、权限:

 Retrofit:

implementation 'com.squareup.retrofit2:retrofit:2.2.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.2.0'

 butterknife:

implementation 'com.jakewharton:butterknife:8.8.1'
implementation 'com.facebook.fresco:fresco:1.5.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'

四.实例网络框架Retrofit:要与butternife联用:

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.but)
    Button but;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        /**
         * 实例网络框架Retrofit:
         * 1.将下载的Json转为Java对象
         * 2.基层http网址
         * 3.构建build
         */
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl("http://www.qubaobei.com/ios/cf/")
                .build();

        //实例接口MenuService:
        MenuService menuService = retrofit.create(MenuService.class);

        //获取到接口,再获取到其getResult方法:
        Call<JavaBean> resualt = menuService.getResualt();

        //拿到方法,通过异步操作,
        resualt.enqueue(new Callback<JavaBean>() {
            @Override
            public void onResponse(Call<JavaBean> call, Response<JavaBean> response) {
                Toast.makeText(MainActivity.this, "加载成功!", Toast.LENGTH_SHORT).show();
                JavaBean body = response.body();
                List<JavaBean.DataBean> data = body.getData();
                Log.i("sadsad",data.toString());

                //recycleView展示模式:
                LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this);
                rv.setLayoutManager(linearLayoutManager);

                //recycleView适配器:
                MyRecycleAdapter myRecycleAdapter = new MyRecycleAdapter(MainActivity.this, data);
                rv.setAdapter(myRecycleAdapter);
            }

            @Override
            public void onFailure(Call<JavaBean> call, Throwable t) {
                Toast.makeText(MainActivity.this, "加载失败!", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

效果如下:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值