一、概述
dependences {
...
compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
}
public interface GitHubService {
@GET("/users/{user}")
Call getUser(@Path("user") String user);
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com")
.build();
GitHubService service = retrofit.create(GitHubService.class);
Call call = service.getUser("userName);
call.enqueue(new Callback(){
@override
public void onResponse(Response response) {
User model = response.body();
if (model == null) {
ResponseBody responseBody = response.errorBody();
if (responseBody != null) {
try {
System.out.println("Error : " + responseBody.string();
} cartch (Exception e) {
e.printStackTrace();
}
}
} else {
System.out.println("User : " + user.toString());
}
}
@override
public void onFailure(Throwable t) {
System.out.println("Failure : " + t.getMessage());
}
});
new Thread() {
@override
public void run() {
// 将上面的 call.enqueue() 代码放在此处执行;杜宇要在请求结束后刷新 UI,则要结合一下 Handler.
}
}.start();