Retrofit的集成及使用

集成:

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

使用:第一步创建api接口

public interface Api {
    @GET("hot")
    Call<List<String>> listHot();

    @GET("recommend")
    Call<List<String>> listRecommend();

    @GET("category")
    Call<List<CategoryItemBean>> listCategory();

    @GET("subject")
    Call<List<SubjectItemBean>> listSubject(@Query("index") int index);

    @GET("game")
    Call<List<AppListItemBean>> listGame(@Query("index") int index);

    @GET("app")
    Call<List<AppListItemBean>> listApp(@Query("index") int index);

    @GET("home")
    Call<HomeBean> listHome(@Query("index") int index);

    @GET("detail")
    Call<AppDetailBean> getAppDetail(@Query("packageName") String packageName);

}

第二步,封装Retrofit对象

public class HeiMaRetrofit {

    private static HeiMaRetrofit sHeiMaRetrofit;

    private Api mApi;

    private Gson mGson = new GsonBuilder().setLenient().create();//设置宽大处理畸形的json

    private static final int CACHE_MAX_SIZE = 5 * 1024 * 1024;

    private HeiMaRetrofit() {
    }

    public void init(Context context) {
        //缓存的路径
        String cacheDir = context.getCacheDir().getAbsolutePath() + "/response";
        File file = new File(cacheDir);
        if (!file.exists()) {
            file.mkdirs();//创建缓存目录
        }
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .cache(new Cache(file, CACHE_MAX_SIZE))
                .addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constant.BASE_URL)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create(mGson))//添加转换器
                .build();
        mApi = retrofit.create(Api.class);
    }

    public static HeiMaRetrofit getInstance() {
        if (sHeiMaRetrofit == null) {
            synchronized (HeiMaRetrofit.class) {
                if (sHeiMaRetrofit == null) {
                    sHeiMaRetrofit = new HeiMaRetrofit();
                }
            }
        }
        return sHeiMaRetrofit;
    }

    public Api getApi() {
        return mApi;
    }

    //在okhttp在回调网络之前我们可以拦截这个响应,做处理在返回回去
    private static Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Response response = chain.proceed(chain.request());
            CacheControl control = new CacheControl.Builder().maxAge(5, TimeUnit.MINUTES).build();
            Response responseAfterModify = response.newBuilder().header("Cache-Control", control.toString()).build();
            return responseAfterModify;
        }
    };

}

第三步:使用Retrofit进行网络请求

  @Override
    protected void startLoadData() {
        Api api = HeiMaRetrofit.getInstance().getApi();//获取API接口
        Call<List<String>> listCall = api.listHot();//获取Call
//        listCall.execute();//同步网络请求
        listCall.enqueue(new Callback<List<String>>() {

            //主线程执行
            @Override
            public void onResponse(Call<List<String>> call, Response<List<String>> response) {
                mDataList = response.body();
                onDataLoadSuccess();
            }

            @Override
            public void onFailure(Call<List<String>> call, Throwable t) {
                onDataLoadFailed();
            }
        });
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 可以与 Retrofit2 集成,以便在应用程序中使用 Retrofit2 进行网络请求。 首先,需要在项目的构建文件中添加 Retrofit2 和其所需的依赖项。通常,可以在 Maven 或 Gradle 文件中添加以下依赖项: Maven: ```xml <dependencies> ... <dependency> <groupId>com.squareup.retrofit2</groupId> <artifactId>retrofit</artifactId> <version>2.9.0</version> </dependency> <dependency> <groupId>com.squareup.retrofit2</groupId> <artifactId>retrofit-converters</artifactId> <version>2.9.0</version> </dependency> <dependency> <groupId>com.squareup.retrofit2</groupId> <artifactId>converter-gson</artifactId> <version>2.9.0</version> </dependency> ... </dependencies> ``` Gradle: ```groovy dependencies { ... implementation 'com.squareup.retrofit2:retrofit:2.9.0' implementation 'com.squareup.retrofit2:converter-gson:2.9.0' ... } ``` 接下来,创建一个 Retrofit 的配置类,用于创建 Retrofit 实例。在该类中,可以设置 Retrofit 的基本配置,如 Base URL、Converter 等。以下是一个简单的示例: ```java @Configuration public class RetrofitConfig { @Value("${api.baseurl}") private String baseUrl; @Bean public Retrofit retrofit() { return new Retrofit.Builder() .baseUrl(baseUrl) .addConverterFactory(GsonConverterFactory.create()) .build(); } } ``` 上述示例中,`api.baseurl` 是一个配置属性,用于指定基本的 API URL。 然后,可以创建一个 Retrofit 的服务接口,定义需要访问的 API 接口。例如: ```java public interface MyApiService { @GET("/users/{id}") Call<User> getUser(@Path("id") String id); } ``` 在上述示例中,`User` 是一个自定义的数据模型类。 最后,在需要使用 Retrofit2 的地方,可以通过依赖注入的方式获取 Retrofit 实例,并使用它创建服务接口的实例。例如: ```java @Service public class MyService { private final MyApiService myApiService; @Autowired public MyService(Retrofit retrofit) { this.myApiService = retrofit.create(MyApiService.class); } public User getUser(String id) { Call<User> call = myApiService.getUser(id); Response<User> response = call.execute(); if (response.isSuccessful()) { return response.body(); } else { // 处理请求失败的情况 return null; } } } ``` 在上述示例中,通过 Retrofit 的 `create()` 方法创建了 `MyApiService` 的实例,并使用该实例进行网络请求。 需要注意的是,上述示例中的代码仅供参考,具体的实现可能会根据项目的需求和架构进行调整。 希望能帮到你!如果还有其他问题,请继续提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值