2026/05/01

오늘의 이야기

 



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


restful



 



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을 통해 직렬화할 수 있습니다.

  • RequestBodyMediaType을 명시해야 서버가 올바르게 인식합니다.

  • 동기 방식으로 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는 더 많은 제어가 가능하지만 코드가 길어지고 복잡해질 수 있습니다. 상황에 따라 적절한 선택이 중요합니다.





 





댓글 없음:

댓글 쓰기

오늘의 이야기

이글 대표 이미지 💡 Eclipse에서 PyDev 오프라인 설치하는 방법 오늘은 PyDev 를 Eclipse에 오프라인으로 설치 하는 방법에 대해 정리해보았습니다. 인터넷 연결이 어려운 환경에서도 Pytho...