Retrofit2的学习笔记

来源:互联网 发布:qihoo360 apk脱壳软件 编辑:程序博客网 时间:2024/05/16 10:09

现在github最火的网络请求开源框架莫过于Retrofit2,它是OKHttp的升级版本
本人也是菜鸟,这是我的学习记录,都是从网上摘要过来学习的,

studio的使用步骤:

1.在module的gradle文件中引入的步骤

compile 'com.squareup.retrofit2:converter-gson:2.0.2'

这里默认集成了retrofti2 gson框架

2.创建服务类和Bean

 public class Contributor {   public String login;    public int contributions;    public Contributor(String login, int contributions) {        this.login = login;        this.contributions = contributions;    }    @Override    public String toString() {        return "Contributor{" +                "login='" + login + '\'' +                ", contributions=" + contributions +                '}';    }}public interface GitHub {    @GET("/repos/{owner}/{repo}/contributors")    Call<List<Contributor>> contributors(            @Path("owner") String owner,            @Path("repo") String repo);}

3.接下来创建Retrofit2的实例,并设置BaseUrl和Gson转换

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

4.创建请求服务,并为网络请求方法设置参数

GitHub gitHubService = retrofit.create(GitHub.class);Call<List<Contributor>> call = gitHubService.contributors("square", "retrofit");try{    Response<List<Contributor>> response = call.execute(); // 同步 还有个异步,下面会讲到    Log.d(TAG, "response:" + response.body().toString());} catch (IOException e) {    e.printStackTrace();}

Call 是Retrofit中重要的一个概念,代表被封装成单个请求/响应的交互行为
通过调用Retrofit2的execute(同步)或者enqueue(异步)方法,发送请求到网络服务器,并返回一个响应(Response).
独立的请求和响应模块
从响应处理分离请求创建
每个实例只能使用一次
Call可以被克隆
支持同步和异步方法

由于call只能被执行一次,所以按照上面的顺序执行,会得到如下错误

java.lang.IllegalStateException: Already executed

我们可以通过clone,来克隆一份call,重新调用

// cloneCall<List<Contributor>> call1 = call.clone();// 5. 请求网络,异步call1.enqueue(new Callback<List<Contributor>>() {    @Override    public void onResponse(Response<List<Contributor>> response, Retrofit retrofit) {        Log.d(TAG, "response:" + response.body().toString());    }    @Override    public void onFailure(Throwable t) {    }});

参数相关
网络访问肯定要涉及到参数请求,Retrofit为我们提供了各式各样的组合方法

固定查询参数

interface SomeService { @GET("/some/endpoint?fixed=query") Call<SomeResponse> someEndpoint();}// 方法调用someService.someEndpoint();// 请求头// GET /some/endpoint?fixed=query HTTP/1.1

动态参数

/ 服务interface SomeService { @GET("/some/endpoint") Call<SomeResponse> someEndpoint( @Query("dynamic") String dynamic);}// 方法调用someService.someEndpoint("query");// 请求头// GET /some/endpoint?dynamic=query HTTP/1.1

动态参数(Map)

// 服务interface SomeService { @GET("/some/endpoint") Call<SomeResponse> someEndpoint( @QueryMap Map<String, String> dynamic);}// 方法调用someService.someEndpoint( Collections.singletonMap("dynamic", "query"));// 请求头// GET /some/endpoint?dynamic=query HTTP/1.1

省略动态参数

interface SomeService { @GET("/some/endpoint") Call<SomeResponse> someEndpoint( @Query("dynamic") String dynamic);}// 方法调用someService.someEndpoint(null);// 请求头// GET /some/endpoint HTTP/1.1

固定+动态参数

interface SomeService { @GET("/some/endpoint?fixed=query") Call<SomeResponse> someEndpoint( @Query("dynamic") String dynamic);}// 方法调用someService.someEndpoint("query");// 请求头// GET /some/endpoint?fixed=query&dynamic=query HTTP/1.1

路径替换

interface SomeService { @GET("/some/endpoint/{thing}") Call<SomeResponse> someEndpoint( @Path("thing") String thing);}//@path 替换@GET里面 { } 包含的部分someService.someEndpoint("bar");// GET /some/endpoint/bar HTTP/1.1

固定头

interface SomeService { @GET("/some/endpoint") @Headers("Accept-Encoding: application/json") Call<SomeResponse> someEndpoint();}someService.someEndpoint();// GET /some/endpoint HTTP/1.1// Accept-Encoding: application/json

动态头

interface SomeService { @GET("/some/endpoint") Call<SomeResponse> someEndpoint( @Header("Location") String location);}someService.someEndpoint("Droidcon NYC 2015");// GET /some/endpoint HTTP/1.1// Location: Droidcon NYC 2015

固定+动态头

interface SomeService { @GET("/some/endpoint") @Headers("Accept-Encoding: application/json") Call<SomeResponse> someEndpoint( @Header("Location") String location);}someService.someEndpoint("Droidcon NYC 2015");// GET /some/endpoint HTTP/1.1// Accept-Encoding: application/json// Location: Droidcon NYC 2015

Post请求,无Body

interface SomeService { @POST("/some/endpoint") Call<SomeResponse> someEndpoint();}someService.someEndpoint();// POST /some/endpoint?fixed=query HTTP/1.1// Content-Length: 0

Post请求有Body

interface SomeService { @POST("/some/endpoint") Call<SomeResponse> someEndpoint( @Body SomeRequest body);}someService.someEndpoint();// POST /some/endpoint HTTP/1.1// Content-Length: 3// Content-Type: greeting//// Hi!

表单编码字段

interface SomeService { @FormUrlEncoded @POST("/some/endpoint") Call<SomeResponse> someEndpoint( @Field("name1") String name1, @Field("name2") String name2);}someService.someEndpoint("value1", "value2");// POST /some/endpoint HTTP/1.1// Content-Length: 25// Content-Type: application/x-www-form-urlencoded//// name1=value1&name2=value2

表单编码字段(Map)

interface SomeService { @FormUrlEncoded @POST("/some/endpoint") Call<SomeResponse> someEndpoint( @FieldMap Map<String, String> names);}someService.someEndpoint( // ImmutableMap是OKHttp中的工具类 ImmutableMap.of("name1", "value1", "name2", "value2"));// POST /some/endpoint HTTP/1.1// Content-Length: 25// Content-Type: application/x-www-form-urlencoded//// name1=value1&name2=value2

动态Url

interface GitHubService { @GET("/repos/{owner}/{repo}/contributors") Call<List<Contributor>> repoContributors( @Path("owner") String owner, @Path("repo") String repo); @GET Call<List<Contributor>> repoContributorsPaginate( @Url String url);}// 调用Call<List<Contributor>> call = gitHubService.repoContributors("square", "retrofit");Response<List<Contributor>> response = call.execute();// 响应结果// HTTP/1.1 200 OK// Link: <https://api.github.com/repositories/892275/contributors?page=2>; rel="next", <https://api.github.com/repositories/892275/contributors?page=3>; rel="last"// 获取到头中的数据String links = response.headers().get("Link");String nextLink = nextFromGitHubLinks(links);// https://api.github.com/repositories/892275/contributors?page=2[/code] 
0 0