본문 바로가기

Java

[Java SpringBoot] Retrofit2 연동 및 사용법 예제

반응형

Retrofit

Retrofit이란?


Retrofit은 HTTP API를 자바 인터페이스 형태로 사용할 수 있는 라이브러리이다. HTTP REST API 형태를 통해 서버와 서버 또는 서버와 클라이언트 간에 서로 정보를 교환 할 수 있다.

스프링부트(SpringBoot) 프로젝트에서 Retrofit 시작하기


먼저 SpringBoot 프로젝트에서 Retrofit 사용을 위해서는 몇가지 의존성을 추가해야한다.

 

Maven 프로젝트일 경우 pom.xml에 아래와 같이 추가한다.

<dependency>
    <groupId>com.squareup.retrofit2</groupId>
    <artifactId>retrofit</artifactId>
    <version>2.9.0</version>
</dependency>
<dependency>
    <groupId>com.squareup.retrofit2</groupId>
    <artifactId>converter-jackson</artifactId>
    <version>2.9.0</version>
</dependency>
<dependency>
    <groupId>com.squareup.retrofit2</groupId>
    <artifactId>converter-gson</artifactId>
    <version>2.9.0</version>
</dependency>
<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>3.12.2</version>
</dependency>

Gradle 프로젝트일 경우 build.gradle에 아래와 같이 추가한다.

implementation group: 'com.squareup.retrofit2', name: 'retrofit', version: '2.9.0'
implementation group: 'com.squareup.retrofit2', name: 'converter-jackson', version: '2.9.0'
implementation group: 'com.squareup.retrofit2', name: 'converter-gson', version: '2.9.0'
implementation group: 'com.squareup.okhttp3', name: 'okhttp', version: '3.12.2'

호출할 API 명세 인터페이스를 구현해야한다. 아래와 같이 구현한다.

 

RestInterface.java

package com.restinterface;

import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.Header;
import retrofit2.http.POST;

public interface RestInterface {
	
   // 반환 타입은 Call<타입>의 제네릭 형태
   @POST("api/test")
   Call<Object> apiTest(@Header("content-type") String contentType, @Body String params);
	
}

※ Retrofit2 어노테이션

  • @GET, @POST, @PUT, @DELETE : HTTP 메소드 지정한다.
  • @Path : 동적으로 URL을 바인딩한다.
  • @Header : HTTP 헤더에 항목 추가
  • @Field : POST방식에서만 사용, form-urlencoded 형태로 데이터를 전송한다.
  • @Query : 쿼리스트링(Query String) 파라미터 추가한다.
  • @Body : GET방식에는 사용할 수 없으며, JSON 스트링형태로 데이터를 전송한다.
  • @URL : 동적인 URL이 필요할 때 사용한다.
  • @Multipart : Multipart/form-data 형태로 Multipart 요청을 보내기 위해 사용한다.

API 명세 구현을 완료 후, RetrofitConfig 클래스를 Bean 생성으로 아래와 같이 구현한다.

 

RetrofitConfig.java

package com.config;

import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.restinterface.RestInterface;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;

@Configuration
public class RetrofitConfig {
	
	private static String API_TEST_URL = "http://localhost:8084/";
	
	@Bean(name="okHttpClient")
	public OkHttpClient okHttpClient() {
		return new OkHttpClient.Builder().connectTimeout(20, TimeUnit.SECONDS)
				.writeTimeout(60, TimeUnit.SECONDS)
				.readTimeout(60, TimeUnit.SECONDS)
				.build();
	}
	
	@Bean(name="commonRetrofit")
	public Retrofit retrofit(@Qualifier("okHttpClient") OkHttpClient client) {
		return new Retrofit.Builder().baseUrl(API_TEST_URL)
				.addConverterFactory(JacksonConverterFactory.create())
				.client(client).build();
	}
	
	@Bean(name="restService")
	public RestInterface restService(@Qualifier("commonRetrofit") Retrofit retrofit) {
		return retrofit.create(RestInterface.class);
	}
	
}

이것으로 REST API 호출할 수 있다. 아래와 같이 RestInterface.java에서 명세한 API를 호출하면 된다.

package com.service;

import com.restinterface.RestInterface;

import retrofit2.Call;
import retrofit2.Response;

import org.springframework.stereotype.Service;

@Service
public class CommonService {
	
	private static final String CONTENT_TYPE = "application/json";
    
	@Autowired
	private RestInterface restService;
	
	public void apiTest() throws Exception {
	
		// HTTP Body값에 넘겨줄 JSON 데이터
		String json = "생략 ...";
		
		Call<Object> call = restService.apiTest(CONTENT_TYPE, json);
		// API 호출
		Response<Object> response = call.execute();
	}
	
}

Reference


https://mangkyu.tistory.com/124

 

[SpringBoot] SpringBoot와 Retrofit2 연동 및 Retrofit2 사용법

1. SpringBoot와 Retrofit 연동 [ SpringBoot와 Retrofit 연동 ] SpringBoot 프로젝트에서 Retrofit2를 사용하기 위해서는 2가지 의존성을 추가해주어야 한다. // https://mvnrepository.com/artifact/com.squar..

mangkyu.tistory.com

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

 

Retrofit

A type-safe HTTP client for Android and Java

square.github.io

 


 

반응형

'Java' 카테고리의 다른 글

자바(JAVA) 버전 별 특징 및 차이  (0) 2021.06.17
자바(Java) 예외처리(Exception)  (0) 2021.06.16