天天看點

網絡請求架構 Retrofit 2 使用入門 網絡請求架構 Retrofit 2 工具類簡單封裝

網絡請求架構 Retrofit 2 工具類簡單封裝

1. 添加依賴

建立一個新的工程後,在你的 build.gradle 檔案裡面添加以下依賴。這些依賴包括 RecyclerView,Retrofit 庫,還有 Google 出品的将 JSON 裝換為 POJO(簡單 Java 對象)的 Gson 庫,以及 Retrofit 的 Gson。

compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2'      

2. 添加網絡權限

要執行網絡操作,我們需要在應用的清單檔案  AndroidManifest.xml  裡面聲明網絡權限。
<uses-permission android:name="android.permission.INTERNET" />      

3. 建立 Retrofit 執行個體

為了使用 Retrofit 向 REST API 發送一個網絡請求,我們需要用  Retrofit.Builder  類來建立一個執行個體,并且配置一個 base URL。

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitClient {

    private static Retrofit retrofit = null;

    public static Retrofit getClient(String baseUrl) {
        if (retrofit==null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}      

4.建立 API 接口

建立一個GitHubService接口,這個接口包含了我們将會用到用于執行網絡請求的方法,比如 GET, POST, PUT, PATCH, 以及 DELETE。在該教程裡面,我們将執行一個 GET 請求。

public interface GitHubService
{           
Call<JK_SJZJ_Bean> getJK_SJZJ_Bean(@Query("shop_id") int shop_id);      
}
           

5.建立 API 工具類

現在我們要建立一個工具類。我們命名為 ApiUtils。該類設定了一個 base URL 常量, 并且通過靜态方法 getGitHubService() 為應用提供GitHubService接口。

public class ApiUtils {

      
這句話是伺服器位址,這裡随便寫的
    public static final String SERVER_ROOT_URL = "http://www.baidu.cn/";

    public static GitHubService getGitHubService() {
        return RetrofitClient.getClient(SERVER_ROOT_URL).create(GitHubService.class);
    }
}      

6.執行請求

要在執行請求前執行這句話,這句話意思就是用它的API工具類定義的服務期位址
GitHubService  gitHubService = ApiUtils.getGitHubService();      
public void Retrofit() {      
用上邊定義的API接口類來拿它的URL,并且把伺服器需要的參數傳給它
       
gitHubService .getJK_SJZJ_Bean(6).enqueue(new Callback<SOAnswersResponse>() {      
@Override public void onResponse(Call<SOAnswersResponse> call, Response<SOAnswersResponse> response) { JK_SJZJ_Bean body = response.body(); Log.d("MainActivity", body);
}

        @Override
        public void onFailure(Call<SOAnswersResponse> call, Throwable t) {
            showErrorMessage();
            Log.d("MainActivity", "error loading from API");

        }
    });
}      

總結

在該教程裡,已經了解了簡單使用 Retrofit 的方法。