반응형
Java로 RESTful API 구현하기: Retrofit2, OkHttp3, Gson 활용

1. Retrofit2를 활용한 API 호출 예제 및 중요 사항
Retrofit2는 Square에서 개발한 HTTP 클라이언트 라이브러리로, RESTful API 호출을 매우 간단하게 만들어줍니다.
예제 코드
public interface ApiService {
@GET("/users/{id}")
Call<User> getUser(@Path("id") int userId);
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.example.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService service = retrofit.create(ApiService.class);
Call<User> call = service.getUser(1);
call.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
if (response.isSuccessful()) {
System.out.println(response.body());
}
}
@Override
public void onFailure(Call<User> call, Throwable t) {
t.printStackTrace();
}
});
중요 사항
- Base URL은 반드시
/로 끝나야 합니다. - GsonConverterFactory를 통해 JSON을 자동으로 객체로 변환합니다.
- 비동기 호출 시
enqueue()를 사용하여 UI 스레드를 차단하지 않습니다.
2. OkHttp3 단독 사용 예제 및 중요 사항
OkHttp3는 낮은 수준의 HTTP 클라이언트로, 더 많은 제어가 가능하며 직접 JSON을 생성하고 전송할 수 있습니다.
예제 코드
import okhttp3.*;
public class JsonPostExample {
public static void main(String[] args) {
OkHttpClient client = new OkHttpClient();
// JSON 문자열 생성
String jsonString = "{ \"name\": \"Kang\", \"age\": 30 }";
// RequestBody 생성
RequestBody body = RequestBody.create(
jsonString,
MediaType.parse("application/json; charset=utf-8")
);
// 요청 생성
Request request = new Request.Builder()
.url("https://your-api-endpoint.com/api/data")
.post(body)
.addHeader("Content-Type", "application/json")
.build();
// 요청 실행
try (Response response = client.newCall(request).execute()) {
System.out.println("응답 코드: " + response.code());
System.out.println("응답 본문: " + response.body().string());
} catch (Exception e) {
e.printStackTrace();
}
}
}
중요 사항
- JSON 문자열은 직접 생성하거나 Gson을 통해 직렬화할 수 있습니다.
RequestBody에MediaType을 명시해야 서버가 올바르게 인식합니다.- 동기 방식으로
execute()를 사용하면 예외 처리를 반드시 해야 합니다.
3. Gson을 이용한 JSON 문자열 생성 및 전송 방법
Gson은 Java 객체를 JSON으로 직렬화하거나 JSON을 객체로 역직렬화하는 데 사용됩니다.
예제 코드
User user = new User("Kang", 30);
Gson gson = new Gson();
String jsonString = gson.toJson(user);
RequestBody body = RequestBody.create(
jsonString,
MediaType.parse("application/json; charset=utf-8")
);
Request request = new Request.Builder()
.url("https://your-api-endpoint.com/api/data")
.post(body)
.build();
// 요청 실행
try (Response response = client.newCall(request).execute()) {
System.out.println("응답 코드: " + response.code());
System.out.println("응답 본문: " + response.body().string());
} catch (Exception e) {
e.printStackTrace();
}
이렇게 생성된 jsonString은 OkHttp3를 통해 서버에 전송할 수 있습니다.
4. Retrofit2 vs OkHttp3 단독 사용 비교
| 항목 | Retrofit2 | OkHttp3 |
|---|---|---|
| 사용 편의성 | 높음 (인터페이스 기반) | 중간 (직접 구성 필요) |
| 유연성 | 중간 (추상화됨) | 높음 (세부 제어 가능) |
| JSON 처리 | 자동 (Gson 연동) | 수동 또는 Gson 병행 |
| 학습 곡선 | 낮음 | 높음 |
5. Retrofit2와 OkHttp3 단독 구현 비교 예제 및 설명
Retrofit2 예제
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.example.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService service = retrofit.create(ApiService.class);
Call<User> call = service.getUser(1);
call.enqueue(...);
OkHttp3 예제
OkHttpClient client = new OkHttpClient();
String jsonString = "{ \"name\": \"Kang\", \"age\": 30 }";
RequestBody body = RequestBody.create(
jsonString,
MediaType.parse("application/json; charset=utf-8")
);
Request request = new Request.Builder()
.url("https://your-api-endpoint.com/api/data")
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
System.out.println("응답 코드: " + response.code());
System.out.println("응답 본문: " + response.body().string());
}
설명
Retrofit2는 선언적 방식으로 API를 정의하고 호출할 수 있어 유지보수가 쉽습니다. 반면 OkHttp3는 더 많은 제어가 가능하지만 코드가 길어지고 복잡해질 수 있습니다. 상황에 따라 적절한 선택이 중요합니다.
반응형
'갑을병정이야기' 카테고리의 다른 글
| Java 로컬 파일 처리, 문자열 검색, 간이 DB 활용 정리 (1) | 2025.09.26 |
|---|---|
| 하청 개발자와 불법파견: 법적 쟁점과 대응 전략 ( 미국에서 발생한 사태를 바라보며 ) (0) | 2025.09.18 |
| 오늘 일과를 위해서, Oracle WebLogic 취약점, Java OkHttp API 호출 등등... (0) | 2025.09.14 |
| DevExtreme DxDataGrid 셀에 버튼 추가하기 (1) | 2025.09.12 |
| Oracle 인덱스 정리: 실전 예제와 설계 팁 (0) | 2025.09.10 |