Call API ใน Java ด้วย Retrofit2
Retrofit เป็น type-safe HTTP client สำหรับ Android และ Java พัฒนาโดย Square ปัจจุบันเป็น version 2 โดยใช้สำหรับ call RESTful API ด้วย OkHttp ในรูปแบบที่ง่ายและสะอาดมาก เมื่อเทียบกับ HTTP client ตัวอื่น
เห็นใน LINE API SDK ใช้ library ตัวนี้ในบทความนี้เลยจะลองใช้ Retrofit2 ใน Java application ดูบ้าง ☺️
Setup
Retrofit สามารถใช้งานด้วย dependency management ทั้ง Maven และ Gradle แต่จะต้องใช้กับ Java 7 และ Android 2.3 ขึ้นไป
Maven
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>retrofit</artifactId>
<version>2.5.0</version>
</dependency>
Gradle
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
แต่อย่าลืมที่จะกำหนด dependency ของ Converter Factory
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
API Declaration
Retrofit จะ model REST endpoint เป็น Java interface ที่เข้าใจง่ายเพราะว่าจะใช้ HTTP method มากำหนดให้แต่ล่ะ method ของ interface และ Retrofit จะสร้าง client จาก interface นี้
public interface GitHubService {
@GET("/repos/{owner}/{repo}/contributors")
Call<List<Contributor>> contributor(
@Path("owner") String owner,
@Path("repo") String repo
);
}
จากตัวอย่างใช้ @GET
เพื่อกำหนดให้ method listRepos
call API ด้วย HTTP GET method และกำหนดหนด path variable เป็น owner และ repo ด้วย @Path
โดยจะไปแทนที่ {owner}
, {repo}
ใน path ของ @GET
Create Client
Retrofit จะสร้าง implementation ของ Service interface ด้วย Builder()
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
GitHubService service = retrofit.create(GitHubService.class);
ที่จะเป็นการกำหนด base URL ของ HTTP client และกำหนด converter ที่ใช้ในการแปลงระหว่าง Object และ JSON ซึ่งรองรับทั้ง Gson
, Jackson
, Moshi
, Protobuf
, Wire
, Simple XML
และ Scalars
(ในที่นี้ใช้ Gson converter)
ใช้ method create()
เพื่อสร้าง implementation ให้กับ Service interface
Call API
หลังจากนั้นสามารถเรียกใช้ method ของ Service ได้เลย ใช้ method execute()
ของ class Call
เพื่อส่ง request แบบ synchronously ไปยัง API endpoint และรอรับ Response
กลับมา พร้อมทั้งแปลง JSON เป็น Object ให้ด้วย converter
Call<List<Contributor>> call = service.contributor("facebook", "react");
List<Contributor> contributors = call.execute().body();
และสามารถเอา body()
ที่เป็นผลลัพธ์ของ API endpoint เพื่อไปใช้งานต่อไป
นอกจากนี้แล้ว Retrofit รองรับ HTTP method ทั้ง POST
, PUT
, DELETE
ซึ่งไม่ได้ใช้ในบทความนี้ แต่ก็สามารถอ่านเพิ่มเติมได้ใน Retrofit document