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模块支持流行的序列化库。
- 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
例如:
这样RequestBody就可以支持Json格式了。Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.github.com") .addConverterFactory(GsonConverterFactory.create()) .build(); GitHubService service = retrofit.create(GitHubService.class);
大概的介绍就是这样了,希望对大家学习有点帮助→_→,最后提点建议,学习还是需要多阅读官方文档,,文档速递