2022年5月28日 星期六

android studio:Retrofit 網路連接套件

 Retrofit這個套用的作用在於網路讀取,它是okhttp這個套件的封裝,在使用上比ohttp更為簡單直觀。使用的方法如下:

一、於build.grade檔案加入Retrofit的庫

implementation 'com.squareup.retrofit2:retrofit:2.9.0'

如取回的資料,需要用gson解析,也可順便加入這個

implementation 'com.squareup.retrofit2:converter-gson:2.7.2'


二、在 AndroidManifest.xml 加入網路權限

<uses-permission android:name="android.permission.INTERNET"/>

三、創建一個類別,用以處理取回的資料(以下要透過下列網站https://jsonplaceholder.typicode.com/)取得id(文章id)、title(文章標題)、body(文章主體)及userId(使用者Id)等值,因此建立了id title body userId屬性。詳細的作法如下,類別名為post。
public class post {
private int id;
private String title;
private String body;
private int 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;
}

public int getUserId() {
return userId;
}

public void setUserId(int userId) {
this.userId = userId;
}

四、創建一個介面,用以統一處理網路連接的方法。以下以get方法為例,自建的類別名設為GetDataService,作法如下:
public interface GetDataService {
@GET("/posts/1")
Call<post> testGet();

}
Get註解裡的/posts/1 為使用時,用get的方法連接API介面的方法,要連接這個API時,完整的連結方法如下:
https://jsonplaceholder.typicode.com/posts/1 ,前半部在使用各種方法時都相同,因此在此介面中,於@後就只放入後面不同的部份,並透過前面的註解,來讓程式選用不同的連接方法。

如果@註解的內容,你要連接的內容,需要動態變換,可以透過{ }來給予動態的參數。如下,透過@Path("參數")中相同的參數,來對應你的註解,達到變換的效果。
@GET("/posts/{userId}")
Call<post> testGet(@Path("userId") int UserId);

如果讀取的資料是多筆資料,則可以透過下列的方法:
//透過傳入參數,變動連結取得資料,並取得多筆資料
@GET("/posts/{userId}/comments")
Call<List<post>> testGets(@Path("userId") int UserId);

如果get方法要傳的連接形式為/comments?postId=1 ,則可以透過@Query註解的方法:

//連接形式為https://jsonplaceholder.typicode.com/comments?postId=1
@GET("comments")
Call<List<post>> testGets2(@Query("postId") int username);
如果get方法要傳的連接形式後面有很多的參數要給予,可以透過@QueryMap註解的方法,再傳的參數直接存在Map中。
//連接形式為https://jsonplaceholder.typicode.com/comments?postId=1
@GET("comments")
Call<List<post>> testGets3(@QueryMap Map<String,String> testData);

五、於Activity使用下列的方法進行網路連結:
//建立Retrofit 實體
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://jsonplaceholder.typicode.com")// 連接的API的連結
.addConverterFactory(GsonConverterFactory.create())// 解析json數據
.build();

GetDataService service = retrofit.create(GetDataService.class);
//Call<post> call = service.testGet(); //取得一筆資料
Call<post> call = service.testGet(1); //透過參數,變動改變連結

call.enqueue(new Callback<post>() {
@Override
public void onResponse(Call<post>call, Response<post> response) {
Log.v("acao", String.valueOf(response.body().getBody()));
}

@Override
public void onFailure(Call<post> call, Throwable t) {

}
});

Call<List<post>> call2 = service.testGets(1);
call2.enqueue(new Callback<List<post>>() {
@Override
public void onResponse(Call<List<post>> call, Response<List<post>> response) {
for (post data : response.body()
) {
Log.d("測試", "id: " + data.getId());
Log.d("測試", "title: " + data.getTitle());
Log.d("測試", "body: " + data.getBody());
Log.d("測試", "userId: " + data.getUserId());
}
}

@Override
public void onFailure(Call<List<post>> call, Throwable t) {

}
});



參考網頁:

https://square.github.io/retrofit/

https://ithelp.ithome.com.tw/articles/10188660

https://tw-hkt.blogspot.com/2020/03/retrofit-java.html

沒有留言:

張貼留言