Retrofit的介绍与使用

retrofit是square公司开发的开源项目,用于java和android的HTTP库,利用注解和okhttp实现和服务器数据交互。

准备:

首先需要导入库的依赖,可以使用Maven

<dependency>
  <groupId>com.squareup.retrofit2</groupId>
  <artifactId>retrofit</artifactId>
<version>2.4.0

也可以使用Gradle

compile 'com.squareup.retrofit2:retrofit:2.4.0

如果无法使用Maven和Gradle也可以手动下载jar包,下载地址速递

需要阅读源码可以进入项目查看https://github.com/square/retrofit

下面开始介绍如何使用:

首先你需要新建一个网络请求的接口:

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

然后新建实现接口的类,在类中创建retrofit实例:

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

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

通过service创建的Call都可以实现远程的异步或同步的请求

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

获取到的repos即为相应信息实体,这就是最简单的一次请求。


下面介绍Retrofit中注释的内容,http请求通过注释来确定请求方式,如@GET()、@POST()这种形式,     

Retrofit支持 URL参数替换和查询参数支持

例如:

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

这里调用groupList方法时将参数groupId自动转换成url中的id参数,实现参数的替换。如果是这样调用,groupList(3),则

调用之后的url是这样的:group/3/users


例如:

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

这样的话将会自动把id作为url中的内容,而sort则会作为查询参数,则调用groupList(3,"人气")调用的url则变为

group/3/users?sort="人气"


支持对象请求体的转换(例如,JSON,协议缓冲区)

例如:

默认情况下,Retrofit只能将HTTP主体反序列化为OkHttp的ResponseBody类型,并且只能接受其RequestBody类型@Body。但Retrofit可以添加转换器以支持其他类型。Retrofit模块支持流行的序列化库。

  • Gsoncom.squareup.retrofit2:converter-gson
  • Jacksoncom.squareup.retrofit2:converter-jackson
  • Moshicom.squareup.retrofit2:converter-moshi
  • Protobufcom.squareup.retrofit2:converter-protobuf
  • Wirecom.squareup.retrofit2:converter-wire
  • Simple XMLcom.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);
这样RequestBody就可以支持Json格式了。

大概的介绍就是这样了,希望对大家学习有点帮助→_→,最后提点建议,学习还是需要多阅读官方文档,,文档速递



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值