| public final class SimpleService { | |
| public static final String API_URL = "https://api.github.com"; | |
| public static class Contributor { | |
| public final String login; | |
| public final int contributions; | |
| public Contributor(String login, int contributions) { | |
| this.login = login; | |
| this.contributions = contributions; | |
| } | |
| } | |
| public interface GitHub { | |
| @GET("/repos/{owner}/{repo}/contributors") | |
| Call<List<Contributor>> contributors( | |
| @Path("owner") String owner, | |
| @Path("repo") String repo); | |
| } | |
| public static void main(String... args) throws IOException { | |
| // Create a very simple REST adapter which points the GitHub API. | |
| Retrofit retrofit = new Retrofit.Builder() | |
| .baseUrl(API_URL) | |
| .addConverterFactory(GsonConverterFactory.create()) | |
| .build(); | |
| // Create an instance of our GitHub API interface. | |
| GitHub github = retrofit.create(GitHub.class); | |
| // Create a call instance for looking up Retrofit contributors. | |
| Call<List<Contributor>> call = github.contributors("square", "retrofit"); | |
| // Fetch and print a list of the contributors to the library. | |
| List<Contributor> contributors = call.execute().body(); | |
| for (Contributor contributor : contributors) { | |
| System.out.println(contributor.login + " (" + contributor.contributions + ")"); | |
| } | |
| } | |
| } |
把代码转移到android项目中去,GsonConverterFactory会找不到。
compile 'com.squareup.retrofit2:retrofit:2.0.1'
在导入这个的基础上需要再导入一个
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
本文介绍了一个使用Retrofit框架调用GitHub API的具体示例。通过创建REST适配器并定义GitHub API接口,实现了获取指定项目的贡献者信息的功能。此外,还解决了在Android项目中引入Gson转换器依赖的问题。

870

被折叠的 条评论
为什么被折叠?



