android 網(wǎng)絡(luò)通信(三):Retrofit 2.0 的使用

概述

A type-safe HTTP client for Android and Java

官網(wǎng)上對(duì)Retrofit 的介紹就只有這么一句話,適用于Android和Java的類型安全的HTTP客戶端,要使用retrofit 完成一個(gè)簡(jiǎn)單的請(qǐng)求也只需要了解使用一下的概念即可。


image.png

簡(jiǎn)單入門

1、添加Retrofit 依賴包

compile 'com.squareup.retrofit2:retrofit:2.3.0'

2、創(chuàng)建一個(gè)Retrofit 實(shí)例

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("http://121.8.250.xx:20012/api/")
    .build();

通過new 一個(gè)builder 后傳入請(qǐng)求的 url,傳入的這個(gè)URL 必須以 "/" 結(jié)尾或者這個(gè)URL 隱含的路徑就是根目錄"/",例如 https://api.github.com。

3、創(chuàng)建一個(gè)管理請(qǐng)求的接口類

public interface APIService {
     //登陸
    @POST("service")
    Call<ResponseBody>  login(@Body LoginRequest loginRequest);
}

LoginRequest 為請(qǐng)求登錄接口的所需的參數(shù)類,如果是使用 GET 方法則如下:

@GET("cardNum/{userId}")
Call<ResponseBody> getUserCardNum(@Path("userId") int userId);

這兩個(gè)例子獲得的返回結(jié)果都在 ResponseBody 中,通過response.body().string() 可以打印出返回結(jié)果,這樣處理比較麻煩,可以根據(jù)返回結(jié)果創(chuàng)建一個(gè)對(duì)應(yīng)的POJO 類來接收返回結(jié)果,只需要在創(chuàng)建retrofit 時(shí)設(shè)置對(duì)應(yīng)的ConvertFactory:

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("http://121.8.250.xx:20012/api/")
    .addConverterFactory(GsonConverterFactory.create())
    .build();

在dependencies 中添加依賴:

compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'

上面的登錄請(qǐng)求更改為:

public interface APIService {
    //登陸
    @POST("service")
    Observable<LoginResult> login(@Body LoginRequest loginRequest);
}

POJO 類的創(chuàng)建可以直接在 AS 中安裝 GSONFormat 插件, 把請(qǐng)求得到的json 數(shù)據(jù)貼進(jìn)去就可以生成對(duì)應(yīng)的 POJO 類了

public class LoginResult {

    private String userName,
                   customerId,
                   resp_msg,
                   tranCode,
                   shopName,
                   resp_code;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getCustomerId() {
        return customerId;
    }

    public void setCustomerId(String customerId) {
        this.customerId = customerId;
    }

    public String getResp_msg() {
        return resp_msg;
    }

    public void setResp_msg(String resp_msg) {
        this.resp_msg = resp_msg;
    }

    public String getTranCode() {
        return tranCode;
    }

    public void setTranCode(String tranCode) {
        this.tranCode = tranCode;
    }

    public String getShopName() {
        return shopName;
    }

    public void setShopName(String shopName) {
        this.shopName = shopName;
    }

    public String getResp_code() {
        return resp_code;
    }

    public void setResp_code(String resp_code) {
        this.resp_code = resp_code;
    }
}

4、接口調(diào)用

APIService api = retrofit.create(APIService .class);
Call<LoginResult> call = api.login(loginRequestParam);

call.enqueue(new Callback<LoginResult>(){  
           @Override  
           public void onResponse(Response<LoginResult> response) {  
               LoginResult loginResult = response.body();
            }  
            @Override  
            public voidonFailure(Throwable t) {  
               //請(qǐng)求失敗處理  
           }  
       });
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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