说来惭愧,retrofit那么热,so火,我居然最近才去研究,不过好歹写了一个项目了,也算是对retrofit有一定的了解吧,那么现在讲讲啦,嘿嘿。
首先项目中加retrofit就得这么搞。
dependencies {
// Retrofit & OkHttp
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
}
前期准备工作:
public class ServiceGenerator {
public static final String API_BASE_URL = "http://your.api-base.url";
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
private static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create());
public static <S> S createService(Class<S> serviceClass) {
Retrofit retrofit = builder.client(httpClient.build()).build();
return retrofit.create(serviceClass);
}
}
public interface GitHubClient {
@GET("/repos/{owner}/{repo}/contributors")
Call<List<Contributor>> contributors(
@Path("owner") String owner,
@Path("repo") String repo
);
}
static class Contributor {
String login;
int contributions;
}
用法如下:
public static void main(String... args) {
// Create a very simple REST adapter which points the GitHub API endpoint.
GitHubClient client = ServiceGenerator.createService(GitHubClient.class);
// Fetch and print a list of the contributors to this library.
Call<List<Contributor>> call =
client.contributors("fs_opensource", "android-boilerplate");
try {
List<Contributor> contributors = call.execute().body();
} catch (IOException e) {
// handle errors
}
for (Contributor contributor : contributors) {
System.out.println(
contributor.login + " (" + contributor.contributions + ")");
}
}
本篇是翻译国外网站的,觉得人已经写的很好了,就没必要自己再写了。
参考网站:https://futurestud.io/blog/retrofit-getting-started-and-android-client