[java] Java Play Framework에서 외부 API와의 연동 방법은 어떻게 되나요?
Java Play Framework는 외부 API와의 연동을 위해 다양한 방법을 제공합니다. 아래는 일반적으로 사용되는 몇 가지 방법입니다.
-
HTTP 클라이언트를 사용하는 방법: Java Play Framework는 기본적으로 HTTP 클라이언트를 지원하므로, 외부 API와의 통신에는
WSClient
를 사용할 수 있습니다. 아래는 예제 코드입니다.// 외부 API 호출을 위한 컨트롤러 메서드 public class MyController extends Controller { private final WSClient ws; @Inject public MyController(WSClient ws) { this.ws = ws; } public CompletionStage<Result> callExternalAPI() { String url = "http://api.example.com"; WSRequest request = ws.url(url); // 필요한 경우 헤더, 파라미터 등을 추가할 수 있습니다. // request.addHeader("Authorization", "Bearer token"); // request.addQueryParameter("param", "value"); return request.get() .thenApply(response -> { // 응답 처리 return ok(response.asJson()); }); } }
-
외부 API 클라이언트를 사용하는 방법: Play Framework에서는 외부 API와의 연동을 쉽게 처리할 수 있는 라이브러리들을 지원합니다. 대표적인 예로는
Retrofit
,Feign
등이 있습니다. 이러한 외부 API 클라이언트를 사용하면 API 호출이 간편해집니다. 아래는Retrofit
을 사용한 예제 코드입니다.// 외부 API 클라이언트 인터페이스 public interface ExternalAPIClient { @GET("/api/resource/{id}") Call<ApiResponse> getResource(@Path("id") String id); } // 외부 API 호출을 위한 컨트롤러 메서드 public class MyController extends Controller { private final ExternalAPIClient client; @Inject public MyController(ExternalAPIClient client) { this.client = client; } public CompletionStage<Result> callExternalAPI() { Call<ApiResponse> call = client.getResource("123"); return call.execute().thenApply(response -> { // 응답 처리 return ok(response.body().toJson()); }); } }
외부 API와의 연동을 위한 방법은 사용하고자 하는 프로젝트의 요구사항에 따라 선택할 수 있습니다. 위에서 소개한 방법들은 대표적인 예시일 뿐이며, 다른 라이브러리나 방식을 사용하여 연동할 수도 있습니다.
더 자세한 내용은 다음 공식 문서를 참조해주세요: