Retrofit入门

xiaoxiao2021-03-01  28

想我一年之前每天都在使用Retrofit,一年之后每天都在使用落后的Volley。

因为平时开发中经常发现demo需要进行网络请求,现场编写一个网络请求的库有点手忙脚乱,所以的话干脆写一篇博客记录下来,以后demo再需要网络请求直接拷贝即可

我之前写过一篇Retrofit的一些注解

Retrofit中的RestApiService

不过最好的文章永远是官方文档

Retrofit官方文档

下面开始愉快的开发:

1 引入两个库

implementation ‘com.squareup.retrofit2:retrofit:2.4.0’ implementation ‘com.squareup.retrofit2:converter-gson:2.0.2’

2 新建一个接口类,用于定义请求的url和返回参数

public interface IService { @GET("app/update") Call<UpdateBean> getUpdateInfo(); }

3 新建一个构造器类,用于生成对应的接口

public class NetUtils { public static final String BASE_URL = "https://api.dushu.io/"; public static IService getService(){ Retrofit retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); return retrofit.create(IService.class); } }

4 具体使用

Call<UpdateBean> call = NetUtils.getService().getUpdateInfo(); call.enqueue(new Callback<UpdateBean>() { @Override public void onResponse(Call<UpdateBean> call, Response<UpdateBean> response) { UpdateBean bean = response.body(); Toast.makeText(MainActivity.this,bean.apkUrl,Toast.LENGTH_LONG).show(); } @Override public void onFailure(Call<UpdateBean> call, Throwable t) { Toast.makeText(MainActivity.this,t.getMessage(),Toast.LENGTH_LONG).show(); Log.d("TAG", "onFailure: "+t.getMessage()); } });
转载请注明原文地址: https://www.6miu.com/read-4150171.html

最新回复(0)