Retrofit 的使用

来源:互联网 发布:linux 定时唤醒 编辑:程序博客网 时间:2024/05/17 21:04

Retrofit

一、概述

Retrofit是Square公司开发的一个类型安全的Java和Android 的HTTP客户端库。

A type-safe HTTP client for Android and Java.

二、简单使用

  • 采用豆瓣电影TOP250的API

1. 添加 gradle 依赖

  • 通过 Android Studio - File - Project Structure - app - Dependencies - “+” - Library Dependency 里搜索添加
  • 通过到官网查询最新依赖,并在 build.gradle 里添加
compile 'com.squareup.retrofit2:retrofit:2.2.0'compile 'com.google.code.gson:gson:2.8.0'compile 'com.squareup.retrofit2:converter-gson:2.2.0'

2. 在 AndroidManifest.xml 里加入网络访问权限

<uses-permission android:name="android.permission.INTERNET"/>

3. 创建 MovieEntity 实体类,解析服务器返回的 JSON 数据

  • 建议使用 Gson 解析,使用 GsonFormatGsonOrXmlFormat 插件一键生成
// 代码不贴了

4. 创建一个Java接口 ApiService 来作为HTTP请求接口

public interface ApiService {    @GET("top250")    Call<MovieEntity> getTopMovies(@Query("start") int start, @Query("count") int count);    }

5. 实例化 Retrofit ,并通过 Retrofit 对象实现上面的接口

String baseUrl = "https://api.douban.com/v2/movie/";Retrofit retrofit = new Retrofit        .Builder()        .baseUrl(baseUrl)        .addConverterFactory(GsonConverterFactory.create())        .build();ApiService apiService = retrofit.create(ApiService.class);

6. 通过接口发起请求

  • 同步调用
MovieEntity movieEntity = call.execute();
  • 异步调用
Call<MovieEntity> call = apiService.getTopMovies(0,10);call.enqueue(new Callback<MovieEntity>() {    @Override    public void onResponse(Call<MovieEntity> call, Response<MovieEntity> response) {        // 处理请求返回的数据    }    @Override    public void onFailure(Call<MovieEntity> call, Throwable t) {        // 请求错误处理    }});

7. 取消请求,即使是正在执行的请求,也能够立即终止。

call.cancel();
  • 效果图
    这里写图片描述

这里写图片描述

源码:https://github.com/bazhancong/SimpleRetrofitDemo


参考:

  1. RxJava 与 Retrofit 结合的最佳实践

  2. Retrofit官网

0 0
原创粉丝点击