在 gradle (Module) 層級的 dependencies 中內加入:
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation "com.squareup.retrofit2:converter-gson:2.9.0"
在AndroidManifet加入網路權限:
<uses-permission android:name="android.permission.INTERNET" />
Interface連線接口
將所有連線的請求方法(GET、POST)及其路徑、參數統一管理
public interface MyAPI {
@GET("todos/1") // 設置一個GET連線,路徑為todos/1
Call<Todos> getTodos(); // 取得的回傳資料用Todos物件接收,連線名稱取為getTodos
@GET("todos/{id}") // 用{}表示路徑參數,@Path會將參數帶入至該位置
Call<Todos> getTodosById(@Path("id") int id);
@POST("todos") // 用@Body表示要傳送Body資料
Call<Todos> postTodos(@Body Todos todos);
}
Todos資料Model
根據 json 的回應資料,設計出 Todos 資料類別,注意欄位名稱要跟API裡的一致
public class Todos {
private int userId;
private int id;
private String title;
private boolean completed;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public boolean isCompleted() {
return completed;
}
public void setCompleted(boolean completed) {
this.completed = completed;
}
}
RetrofitManager連線基底
設置連線網站(https://jsonplaceholder.typicode.com/) 和 converter
public class RetrofitManager {
// 以Singleton模式建立
private static RetrofitManager mInstance = new RetrofitManager();
private MyAPI myAPI;
private RetrofitManager() {
// 設置baseUrl即要連的網站,addConverterFactory用Gson作為資料處理Converter
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://jsonplaceholder.typicode.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
myAPI = retrofit.create(MyAPI.class);
}
public static RetrofitManager getInstance() {
return mInstance;
}
public MyAPI getAPI() {
return myAPI;
}
}
GET
private void retrofitGet() {
// 1. 宣告MyAPI
MyAPI myAPI;
// 2. 透過RetrofitManager取得連線基底
myAPI = RetrofitManager.getInstance().getAPI();
// 3. 建立連線的Call,此處設置call為myAPI中的getTodos()連線
Call<Todos> call = myAPI.getTodos();
// 若要設置call為myAPI中的getTodosById()連線,更改call的method並將參數傳入就行
// Call<Todos> call = myAPI.getTodosById(2);
// 4. 執行call
call.enqueue(new Callback<Todos>() {
@Override
public void onResponse(Call<Todos> call, Response<Todos> response) {
// 連線成功
// 回傳的資料已轉成Todos物件,可直接用get方法取得特定欄位
String title = response.body().getTitle();
Log.d("get", title);
}
@Override
public void onFailure(Call<Todos> call, Throwable t) {
// 連線失敗
t.printStackTrace();
}
});
}
POST
private void retrofitPost() {
MyAPI myAPI;
myAPI = RetrofitManager.getInstance().getAPI();
// 建立要POST的物件
Todos todos = new Todos(1,1,"delectus aut autem",false);
// 將物件作為postTodos的參數
Call<Todos> call = myAPI.postTodos(todos);
call.enqueue(new Callback<Todos>() {
@Override
public void onResponse(Call<Todos> call, Response<Todos> response) {
// 連線成功
String title = response.body().getTitle();
Log.d("post", title);
}
@Override
public void onFailure(Call<Todos> call, Throwable t) {
// 連線失敗
t.printStackTrace();
}
});
}
謝謝大家願意花時間閱讀,小弟弟我在此鞠躬