初探Retrofit使用方法

概念

Retrofit框架是Square公司出品的網絡框架,效率快、實現簡單。運用註解和動態代理,極大簡化網絡請求繁瑣步驟

特點

    性能好、處理快,使用簡單;默認使用okhttp處理網絡請求;默認使用Gson解析。

常用註解接口

    Retrifit採用註解方式標註方法,常用接口如下:

@GET:GET網絡請求方式
@POST:POST網絡請求方式
GET請求相關:
@Headers:頭參數信息
@Path:路徑參數
@Query:查詢參數,將在url中追加類似page=1這樣的參數
@QueryMAP:查詢參數集合,將在url中追加類似type=text&count=30這樣的參數
POST請求相關:
@FromUrlEncoded:對錶單域中填寫的內容進行編碼處理,避免亂碼
@Field:指定form表單域中每個控件的name及值
@FieldMap:表單域集合
@Multipart:Post提交分塊請求,上傳文件時使用
@Part:POST提交分塊請求
@Body:post提交分塊請求

實現簡單網絡請求

步驟

1、定義一個接口(封裝url和請求參數)
2、實例化Retrofit
3、通過Retrofit實例創建接口服務對象
4、接口服務對象調用接口方法,獲得Call對象
5、Call對象執行請求(同步、異步)

    Demo

    1、創建接口

public interface GitHubApi {
    //使用GET註解,參數爲baseUrl後邊的路徑
    @GET("repos/{owner}/{repo}/contributors")
    //返回類型爲帶有泛型的Call,使用Path註解標註參數
Call<ResponseBody> contributorsBySimpleGetCall(@Path("owner") 
String  owner,  @Path("repo") String repo);
}
2、創建Retroift實例
//其中指定了baseUrl
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com/")
     .build();

3、通過Retrofit實例創建接口服務對象

GitHubApi repo = retrofit.create(GitHubApi.class);

4、調用接口中自定義方法獲取Call對象

 Call<ResponseBody> call = repo.contributorsBySimpleGetCall(mUserName,  mRepo);

5、調用Call對象enqueue()方法執行網絡請求

//注意,callback在主線程中執行
call.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
        try {
            Gson gson = new Gson();
            ArrayList<Contributor> contributorsList = gson.fromJson(response.body().string(),
new TypeToken<List<Contributor>>(){}.getType());
            for (Contributor contributor : contributorsList){
                Log.d("login",contributor.getLogin());
                Log.d("contributions",contributor.getContributions()+"");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void onFailure(Call<ResponseBody> call, Throwable t) {

    }
});

添加轉換器

 在上面的例子中通過獲取ResponseBody後,我們自己使用Gson來解析接收到的Json格式數據。在Retrofit中當創建一個Retrofit實例的時候可以爲其添加一個Json轉換器,這樣就會自動將Json格式的響應體轉換爲所需要的Java對象。
 在這裏我們需要爲retrofit添加gson轉換器的依賴。添加過converter-gson後不用再添加gson庫。在converter-gson中已經包含gson。

1、創建Javabean

   public class Contributor {
    private String login;
    private Integer contributions;
    public String getLogin() {
        return login;
    }
    public void setLogin(String login) {
        this.login = login;
    }
    public Integer getContributions() {
        return contributions;
    }
    public void setContributions(Integer contributions) {
        this.contributions = contributions;
    }
}
2、修改接口,返回的不再是Response,而是List<Contributor>
@GET("repos/{owner}/{repo}/contributors")
Call<List<Contributor>> contributorsByAddConverterGetCall(@Path("owner") String owner, @Path("repo") String repo);

3、創建retrofit時添加轉換器

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://api.github.com/")
        .addConverterFactory(GsonConverterFactory.create())
        .build();

4、修改調用

GitHubApi repo = retrofit.create(GitHubApi.class);
Call<List<Contributor>> call = repo.contributorsByAddConverterGetCall(mUserName, mRepo);
call.enqueue(new Callback<List<Contributor>>() {
    @Override
    public void onResponse(Call<List<Contributor>> call, Response<List<Contributor>> response) {
        List<Contributor> contributorList = response.body();
        for (Contributor contributor : contributorList){
            Log.d("login", contributor.getLogin());
            Log.d("contributions", contributor.getContributions() + "");
        }
    }
    @Override
    public void onFailure(Call<List<Contributor>> call, Throwable t) {

    }
});

簡單的Retrofit調用過程就是如此

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章