1. 程式人生 > >retrofit的簡單使用(請求網路資料)

retrofit的簡單使用(請求網路資料)

倒入依賴

implementation 'com.squareup.retrofit2:retrofit:2.0.2'
implementation 'com.squareup.okhttp3:okhttp:3.1.2'
implementation 'com.google.code.gson:gson:2.2.4'
implementation 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'

寫一個網路資料的bean類

寫一個所有介面都一樣的介面頭 方便呼叫

public class Constant {
    public static final String CONSTANT_GET = "https://www.zhaoapi.cn/";
}

寫一個介面 繼續拼接往介面頭後面拼接的介面

public interface Api {
    @GET("product/getProducts")
    Call<UserBean> getCall(@Query("pscid") int id);
}

 MainActivity中的程式碼

建立一個retrofit物件將大部分一樣的介面頭部從constant類中拿出

Retrofit build = new Retrofit.Builder().baseUrl(Constant.CONSTANT_GET)
        .addConverterFactory(GsonConverterFactory.create())
        .build();
拼接上Api類中的地址部分
Api api = build.create(Api.class);
拼接上Api類中的id
Call<UserBean> call = api.getCall(1);
請求
call.enqueue(new Callback<UserBean>() {
    @Override
    public void onResponse(Call<UserBean> call, Response<UserBean> response) {

        String title = response.body().getData().get(0).getTitle();
        Toast.makeText(MainActivity.this,title,Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onFailure(Call<UserBean> call, Throwable t) {
        Toast.makeText(MainActivity.this,"失敗",Toast.LENGTH_SHORT).show();
    }
});