濟飛.png
Retrofit是網絡請求的一個庫,是在okhttp上面有包裝了一層,封裝了數據轉換,get,post等等。我覺得最主要是封裝了數據轉換吧,什么json數據轉換什么的。
大概說個例子吧,下面例子是通過get方法獲取我的github賬戶的所有倉庫。
建立數據處理類型
估計是服務器的數據最后都轉變成下面這個java類型吧,便于java處理
package com.wenfengtou.retrofitdemo;
/**
* Created by wenfeng on 2017-04-12.
*/
public class RepositoryBean {
String full_name;
String html_url;
int contributions;
@Override
public String toString() {
return full_name + " (" + contributions + ")";
}
}
訪問服務器
GitHubService是一個接口,據說可以被Retrofit轉化成一個類,然后就能調用里面的方法queryUserRepos了,這個方法就是通過get的方式獲取數據,返回一個RepositoryBean的數據。
package com.wenfengtou.retrofitdemo;
/**
* Created by wenfeng on 2017-04-12.
*/
import java.util.List;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.GET;
import retrofit2.http.Path;
import java.util.List;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.GET;
import retrofit2.http.Path;
public interface GitHubService {
@GET("users/{users}/repos")
Call<List<RepositoryBean>> queryUserRepos(
@Path("users") String users);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
}
main函數調用
首先通過retrofit.create獲取到gitHubService 服務,然后調用這個服務的方法就ok啦。
GitHubService gitHubService = retrofit.create(GitHubService.class);
Call<List<RepositoryBean>> call = gitHubService.queryUserRepos("wenfengtou");
結果.png
例子傳送門
https://github.com/wenfengtou/RetrofitDemo
參考:
Retrofit