A type-safe HTTP client for Android and Java
Retrofit requires at minimum Java 8+ or Android API 21+.
引入依赖
MAVEN
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>retrofit</artifactId>
<version>(insert latest version)</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.squareup.retrofit2/retrofit -->
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>retrofit</artifactId>
<version>2.9.0</version>
</dependency>
GRADLE
implementation 'com.squareup.retrofit2:retrofit:(insert latest version)'
转换库
例如GSON
implementation 'com.squareup.retrofit2:converter-gson:(insert latest version)'
<!-- https://mvnrepository.com/artifact/com.squareup.retrofit2/converter-gson -->
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>converter-gson</artifactId>
<version>2.9.0</version>
</dependency>
基本流程
使用范例
定义实体类
public class Repo {
private int id;
private String name;
@SerializedName("html_url")
private String htmlUrl;
@Override
public String toString() {
return "Repo{" +
"id=" + id +
", name='" + name + '\'' +
", htmlUrl='" + htmlUrl + '\'' +
'}';
}
// 省略getter和setter方法
}
定义接口
public interface GitHubService {
@GET("users/{user}/repos")
Call<List<Repo>> listRepos(@Path("user") String user);
}
创建Retrofit对象
public static void main(String[] args) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
// 省略其他部分代码
}
生成接口实例
GitHubService service = retrofit.create(GitHubService.class);
获得Call对象
Call<List<Repo>> repos = service.listRepos("Square");
异步或同步请求
repos.enqueue(new Callback<List<Repo>>() {
@Override
public void onResponse(Call<List<Repo>> call, Response<List<Repo>> response) {
for (Repo repo : response.body()) {
System.out.println(repo);
}
}
@Override
public void onFailure(Call<List<Repo>> call, Throwable throwable) {
System.out.println("访问失败!");
}
});
System.out.println("main线程结束!");
On Android, callbacks will be executed on the main thread. On the JVM, callbacks will happen on the same thread that executed the HTTP request.
运行效果
main线程结束!
Repo{id=36665193, name='Aardvark', htmlUrl='https://github.com/square/Aardvark'}
Repo{id=60724575, name='Ackbar', htmlUrl='https://github.com/square/Ackbar'}
Repo{id=89733456, name='active_merchant_square', htmlUrl='https://github.com/square/active_merchant_square'}
Repo{id=48068599, name='active_record-sql_analyzer', htmlUrl='https://github.com/square/active_record-sql_analyzer'}
Repo{id=7923123, name='android-times-square', htmlUrl='https://github.com/square/android-times-square'}
Repo{id=271357426, name='anvil', htmlUrl='https://github.com/square/anvil'}
Repo{id=12226292, name='apropos', htmlUrl='https://github.com/square/apropos'}
//...