[Android 知识点] 网络请求框架Retrofit使用

介绍

Retrofit将Http请求转化成一个Java接口

public interface GitHubService {
  @GET("users/{user}/repos")
  Call<List<Repo>> listRepos(@Path("user") String user);
}

Retrofit类实现GitHubService接口

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.github.com/")
    .build();

GitHubService service = retrofit.create(GitHubService.class);

从GitHubService 得到每一个call都会进行一次同步或异步网络请求到服务器

Call<List<Repo>> repos = service.listRepos("octocat");

用注解的方式描述Http请求
- 支持URL参数
- 实体转换,如JSON
- 多请求和文件上传

API介绍

每一个方法,必须含有一个Http注解,内置5个注解:

GET, POST, PUT, DELETE, HEAD,在注解中指定相关资源

REQUEST METHOD

@GET("users/list")

也可以指定查询参数

@GET("users/list?sort=desc")

也可以指定变参

@GET("{name}")
Call<User> getUser(@Path("name") String name);

URL 操作

URL中的路劲参数需要用@Path进行注解,添加查询参数,使用@Query进行注解

@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId);

也可以添加参数

@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort);

也可以添加参数组合,使用Map集合

@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options);

REQUEST BODY

一个实体可以用@Body注解进行指定

@POST("users/new")
Call<User> createUser(@Body User user)

可以使用转化器,如果没有,只能用RequestBody

FORM ENCODED AND MULTIPART

表格数据可以用 @FormUrlEncoded进行注解

@FormUrlEncoded
@POST("user/edit")
Call<User> updateUser(@Field("first_name") String first, @Field("last_name") String last);

多个请求可以用@Multipart进行注解,每一个部分可以用@Part进行注解

@Multipart
@PUT("user/photo")
Call<User> updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description);

HEADER 操作

用 @Headers进行注解

@Headers("Cache-Control: max-age=640000")
@GET("widget/list")
Call<List<Widget>> widgetList();
@Headers({
    "Accept: application/vnd.github.v3.full+json",
    "User-Agent: Retrofit-Sample-App"
})
@GET("users/{username}")
Call<User> getUser(@Path("username") String username);

也可以在参数中进行注解

@GET("user")
Call<User> getUser(@Header("Authorization") String authorization)

SYNCHRONOUS VS. ASYNCHRONOUS

Call实例可以同步执行,或者异步执行,但只能用一个,可以使用clone()创建新的实例。

回调函数会被执行在主线程。

  • 同步使用:execute()
  • 异步使用:enqueue()
 mService.getAnswers().enqueue(new Callback<SOAnswersResponse>() {
    @Override
    public void onResponse(Call<SOAnswersResponse> call, Response<SOAnswersResponse> response) {

        if(response.isSuccessful()) {
            mAdapter.updateAnswers(response.body().getItems());
            Log.d("MainActivity", "posts loaded from API");
        }else {
            int statusCode  = response.code();
            // handle request errors depending on status code
        }
    }

    @Override
    public void onFailure(Call<SOAnswersResponse> call, Throwable t) {
       showErrorMessage();
        Log.d("MainActivity", "error loading from API");

    }
});

其中,onResponse表示成功回调函数,onFailure表示失败回调函数。

Retrofit Configuration

实体转换 

  • Gson: com.squareup.retrofit2:converter-gson
  • Jackson: com.squareup.retrofit2:converter-jackson
  • Moshi: com.squareup.retrofit2:converter-moshi
  • Protobuf: com.squareup.retrofit2:converter-protobuf
  • Wire: com.squareup.retrofit2:converter-wire
  • Simple XML: com.squareup.retrofit2:converter-simplexml
  • Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars

下面是一个例子:

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.github.com")
    .addConverterFactory(GsonConverterFactory.create())
    .build();

GitHubService service = retrofit.create(GitHubService.class);

也可以自定义转换器

方法:创建一个类继承 Converter.Factory class and pass in an instance when building your adapter.

依赖

GRADLE

compile ‘com.squareup.retrofit2:retrofit:2.1.0’

混淆

# Platform calls Class.forName on types which do not exist on Android to determine platform.
-dontnote retrofit2.Platform
# Platform used when running on RoboVM on iOS. Will not be used at runtime.
-dontnote retrofit2.Platform$IOS$MainThreadExecutor
# Platform used when running on Java 8 VMs. Will not be used at runtime.
-dontwarn retrofit2.Platform$Java8
# Retain generic type information for use by reflection by converters and adapters.
-keepattributes Signature
# Retain declared checked exceptions for use by a Proxy instance.
-keepattributes Exceptions

案例

  1. 配置Gradle
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.google.code.gson:gson:2.6.1'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
  1. 添加网络权限
<uses-permission android:name="android.permission.INTERNET" />
  1. 生成Gson实体类

可以借助工具jsonschema2pojo ,需要vpn

也可以借助AS的一个插件:Json2Pojo 进行Gson实体类的自动生成

4.自己编写一个接口

public interface xxxxxService {
  @GET("users/{user}/repos")
  Call<List<Repo>> listRepos(@Path("user") String user);
}

5.构造一个Retrofit

etrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.github.com/")
    .build();

GitHubService service = retrofit.create(GitHubService.class);

6.获取一个网络请求Call实例

Call<List<Repo>> repos = service.listRepos("octocat");

7.进行同步/异步调用

// 同步调用
List<Repo> data = repos.execute(); 

// 异步调用
repos.enqueue(new Callback<List<Repo>>() {
            @Override
            public void onResponse(Call<List<Repo>> call, Response<List<Repo>> response) {
                List<Repo> data = response.body();
            }

            @Override
            public void onFailure(Call<List<Repo>> call, Throwable t) {
                t.printStackTrace();
            }
        });
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值