1、Retrofit是什么?
2、Retrofit、Volley、OkHttp等的关系
3、Retrofit的示例
添加依赖和权限
compile 'com.squareup.retrofit:retrofit:2.0.1-beta2'
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
// AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
public interface APIInterface {
@GET("/users/{user}")
Call<TestModel> repo(@Path("user") String user);
hostname和port会在构造Retrofit对象时,添加一个baseUrl(https://api.github.com)。在此GET的意思是,发送一个GET请求,请求地址为:baseUrl+"/users/{user}"。{user}类似于占位符的作用,具体类型由repo(@Path("user")String user)指定,这里表示{user}将是一段字符串。
定义Model
public class TestModel {
private String login;
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
}
进行连接通信
Retrofit retrofit= new Retrofit.Builder()
.baseUrl("https://api.github.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
注意:这里添加的baseUrl和GsonConverter,前者表示要访问的网站是,后者是添加了一个转换器。
APIInterface service = retrofit.create(APIInterface.class); 使用ApiInterface创建一个请求对象:
Call<TestModel> model = service.repo("Guolei1130");
注意这里的 .repo("Guolei1130") 取代了前面的 {user}。到这里,我们要访问的地址就成了:
model.enqueue(new Callback<TestModel>() {
@Override
public void onResponse(Call<TestModel> call, Response<TestModel> response) {
// Log.e("Test", response.body().getLogin());
System.out.print(response.body().getLogin());
}
@Override
public void onFailure(Call<TestModel> call, Throwable t) {
System.out.print(t.getMessage());
}
}); 至此,我们就利用Retrofit完成了一次网络请求。
423




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



