Android雜談:Retrofit初體驗

濟飛.png

Retrofit是網(wǎng)絡請求的一個庫,是在okhttp上面有包裝了一層,封裝了數(shù)據(jù)轉(zhuǎn)換,get,post等等。我覺得最主要是封裝了數(shù)據(jù)轉(zhuǎn)換吧,什么json數(shù)據(jù)轉(zhuǎn)換什么的。
大概說個例子吧,下面例子是通過get方法獲取我的github賬戶的所有倉庫。

建立數(shù)據(jù)處理類型

估計是服務器的數(shù)據(jù)最后都轉(zhuǎn)變成下面這個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是一個接口,據(jù)說可以被Retrofit轉(zhuǎn)化成一個類,然后就能調(diào)用里面的方法queryUserRepos了,這個方法就是通過get的方式獲取數(shù)據(jù),返回一個RepositoryBean的數(shù)據(jù)。

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函數(shù)調(diào)用

首先通過retrofit.create獲取到gitHubService 服務,然后調(diào)用這個服務的方法就ok啦。

        GitHubService gitHubService = retrofit.create(GitHubService.class);

        Call<List<RepositoryBean>> call = gitHubService.queryUserRepos("wenfengtou");

結(jié)果.png

例子傳送門
https://github.com/wenfengtou/RetrofitDemo

參考:
Retrofit

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容