iT邦幫忙

2021 iThome 鐵人賽

DAY 6
0
Mobile Development

android studio 30天學習筆記系列 第 6

android studio 30天學習筆記-day 6-介紹retrofit(二)

今天要來了解上一篇的各個步驟

1.創建資料類別
有個快速生成data class的插件,可以從File->setting->Plugins->搜尋GsonFormat並install,install完後重啟Android Studio

https://ithelp.ithome.com.tw/upload/images/20210712/201389667YHLgHgvtQ.png

創個新的class,右鍵 Generate->Gsonformat,把gson資料貼上去
https://ithelp.ithome.com.tw/upload/images/20210712/20138966jWtKoe1yDy.png
按下ok後,可以修改其資料型態、變數
https://ithelp.ithome.com.tw/upload/images/20210712/20138966rmHm1EnlA3.png
按下ok後,會生成對應的data class

public class Datamm {

    /**
     * userId : 1
     * id : 1
     * title : sunt aut facere repellat provident occaecati excepturi optio reprehenderit
     * body : quia et suscipit
     suscipit recusandae consequuntur expedita et cum
     reprehenderit molestiae ut ut quas totam
     nostrum rerum est autem sunt rem eveniet architecto
     */

    private int userId;
    private int id;
    private String title;
    private String body;

    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 String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }
}

當然也可以自己手打啦,首先設定對應gson格式的data

public class Datamm {
    private int userId;
    private int id;
    private String title;
    private String body;
}

然後按右鍵Generate->getter and setter,全部選取後按下Ok,也會出現跟上面一樣的data class
https://ithelp.ithome.com.tw/upload/images/20210712/20138966VbM4HimoNJ.png

建立retrofit

Retrofit retrofit=new Retrofit.Builder() 
                .baseUrl("https://jsonplaceholder.typicode.com/") //連接你要的uri
                .addConverterFactory(GsonConverterFactory.create()) //gson解析
                .build();

interface
@GET

    @GET("posts")
    Call<DataItem> getPosts();  
    
    @GET("posts/{id}") //可以用@Path將新的參數帶入{}
    Call<DataItem> getPosts(@Path("id") int id);  

@POST

    @POST("posts") // @Body表示要傳送Body資料
    Call<DataItem> getPosts(@Body Posts posts);

@PUT

    @PUT("posts")
    Call<DataItem> getPosts();  

@DELETE

    @DELETE("posts")
    Call<DataItem> getPosts();  

最後使用enqueue進行異步操作的請求

 ApiGet apiGet =retrofit.create(ApiGet.class);
        Call<DataItem> call =apiGet.getPosts(); //呼叫call連線服務
        
        call.enqueue(new Callback<DataItem>() { //透過 Callback 來等待回傳成功或失敗的資料
            @Override
            public void onResponse(Call<DataItem> call, Response<DataItem> response) {
                Log.d("API", "id: " + response.body().getId());
                Log.d("API", "User Id: " + response.body().getUserId());
                Log.d("API", "Title: " + response.body().getTitle());
                Log.d("API", "Text: " + response.body().getText());
            }

            @Override
            public void onFailure(Call<DataItem> call, Throwable t) {
                Log.d("API", "fail");
            }
        });

這樣就完成了


上一篇
android studio 30天學習筆記-day 5-介紹retrofit(一)
下一篇
android studio 30天學習筆記-day 7-介紹okhttp
系列文
android studio 30天學習筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言