本文是基于Retrofit2进行学习。首先你要知道Retrofit是一个网络请求框架,它的api 定义可以查阅官网.
从零开始搭建一个Retrofit的例子
以下示例会分别列出Retrofit 1.9
和Retrofit 2
的区别用法
添加依赖
Retrofit 1.9
1 | dependencies { |
Retrofit 2
1 | dependencies { |
Api服务核心类
ServiceGenerator是项目的http核心类,专门用于封装http请求的基类。
Retrofit 1.9
1 | public class ServiceGenerator { |
Retrofit 2
1 | public class ServiceGenerator { |
Json解析
Retrofit 1.9默认带有Gson的支持。Retorfit2就需要自定义添加支持。
1 | compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2' |
public interface GitHubClient {
@GET(“/repos/{owner}/{repo}/contributors”)
List
@Path(“owner”) String owner,
@Path(“repo”) String repo
);
}1
2
Retrofit 2
public interface GitHubClient {
@GET(“/repos/{owner}/{repo}/contributors”)
Call> contributors(
@Path(“owner”) String owner,
@Path(“repo”) String repo
);
}1
2
### Model类 ###
class Contributor {
String login;
int contributions;
}1
2
3
4
### 请求 ###
Retrofit 1.9
GitHubClient client = ServiceGenerator.createService(GitHubClient.class);
// Fetch and print a list of the contributors to this library.
List<Contributor> contributors =
client.contributors("fs_opensource", "android-boilerplate");
for (Contributor contributor : contributors) {
System.out.println(
contributor.login + " (" + contributor.contributions + ")");
}
1 |
|
GitHubClient client = ServiceGenerator.createService(GitHubClient.class);
// Fetch and print a list of the contributors to this library.
Call<List<Contributor>> call =
client.contributors("lzyzsd", "Awesome-RxJava");
List<Contributor> contributors = null;
try {
contributors = call.execute().body();
for (Contributor contributor : contributors) {
System.out.println(
contributor.login + " (" + contributor.contributions + ")");
}
} catch (IOException e) {
e.printStackTrace();
}
1 |
|
public class ServiceGenerator {
public static final String API_BASE_URL = "http://your.api-base.url";
private static RestAdapter.Builder builder = new RestAdapter.Builder()
.setEndpoint(API_BASE_URL)
.setClient(new OkClient(new OkHttpClient()));
public static <S> S createService(Class<S> serviceClass) {
return createService(serviceClass, null, null);
}
public static <S> S createService(Class<S> serviceClass, String username, String password) {
if (username != null && password != null) {
// concatenate username and password with colon for authentication
String credentials = username + ":" + password;
// create Base64 encodet string
final String basic =
"Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
builder.setRequestInterceptor(new RequestInterceptor() {
@Override
public void intercept(RequestFacade request) {
request.addHeader("Authorization", basic);
request.addHeader("Acceppt", "application/json");
}
});
}
RestAdapter adapter = builder.build();
return adapter.create(serviceClass);
}
}1
2
Retrofit 2
public class ServiceGenerator {
public static final String API_BASE_URL = “http://api.github.com“;
private static OkHttpClient httpClient = new OkHttpClient();
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();
return retrofit.create(serviceClass);
}
public static <S> S createService(Class<S> serviceClass,String username,String password){
if (username != null && password != null) {
String credentials = username + ":" + password;
final String basic =
"Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
httpClient.interceptors().clear();
httpClient.interceptors().add(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
Request.Builder requestBuilder = original.newBuilder()
.header("Authorization", basic)
.header("Accept", "applicaton/json")
.method(original.method(), original.body());
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
}
Retrofit retrofit = builder.client(httpClient).build();
return retrofit.create(serviceClass);
}
}1
2
3
## 添加LoginServer ##
Retrofit 1.9
public interface LoginService {
@POST(“/login”)
User basicLogin();
}1
2
Retrofit 2
public interface LoginService {
@POST(“/login”)
Call
}1
2
3
## 调用示例 ##
Retrofit 1.9
LoginService loginService =
ServiceGenerator.createService(LoginService.class, “user”, “secretpassword”);
User user = loginService.basicLogin();1
2
Retrofit 2
LoginService loginService =
ServiceGeneratorcreateService(LoginService.class, “user”, “secretpassword”);
Call
User user = call.execute().body();
```