게으른 개발자의 끄적거림

Java 알림톡 보내는 방법

끄적잉 2024. 5. 27. 21:54
반응형
반응형

Java를 사용하여 알림톡(카카오톡 메시지) 보내는 방법을 자세하게 설명하겠습니다. 이 작업을 수행하기 위해서는 카카오톡의 비즈니스 플랫폼인 카카오톡 비즈니스 메시지 API를 사용해야 합니다. 다음은 Java를 사용하여 알림톡을 보내는 과정에 대한 상세한 설명입니다.

 


### 1. 카카오톡 비즈니스 메시지 API 소개

카카오톡 비즈니스 메시지 API는 카카오톡을 통해 메시지를 보낼 수 있는 기능을 제공합니다. 이를 통해 기업은 사용자에게 알림, 광고, 홍보 등을 효과적으로 전달할 수 있습니다. 알림톡은 사용자에게 중요한 정보를 전달하는데 사용되며, 다양한 형식의 메시지를 지원합니다.

 

 

### 2. 준비 작업

#### 2.1. 카카오톡 비즈니스 계정 등록

카카오톡 비즈니스 메시지를 사용하려면 먼저 카카오 비즈니스 계정을 등록해야 합니다. 이를 위해 다음 단계를 따릅니다:

1. [카카오 디벨로퍼스](https://developers.kakao.com/)에 접속합니다.
2. 카카오 계정으로 로그인합니다.
3. 애플리케이션을 생성합니다.
4. 비즈니스 채널과 애플리케이션을 연결합니다.
5. 비즈니스 메시지 API 사용 신청을 완료합니다.

#### 2.2. API 키 발급

비즈니스 메시지 API를 사용하기 위해서는 API 키가 필요합니다. 카카오 디벨로퍼스의 애플리케이션 설정에서 API 키를 확인할 수 있습니다. 이 키는 API 호출 시 인증을 위해 필요합니다.

 

 

### 3. Java 환경 설정

Java 환경에서 HTTP 요청을 보내기 위해 라이브러리가 필요합니다. 가장 일반적으로 사용되는 라이브러리는 Apache HttpClient입니다. Maven 프로젝트를 사용하여 의존성을 관리할 수 있습니다.

#### 3.1. Maven 설정

프로젝트의 `pom.xml` 파일에 Apache HttpClient 의존성을 추가합니다:

```xml
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>
```

이제 Java에서 HTTP 요청을 보낼 준비가 되었습니다.

 

 

### 4. 알림톡 보내기

알림톡을 보내기 위해서는 HTTP POST 요청을 사용하여 메시지 전송 API를 호출해야 합니다. 다음은 Java 코드를 통해 알림톡을 보내는 방법입니다.

#### 4.1. HTTP 클라이언트 설정

먼저, HttpClient를 설정하고 POST 요청을 구성합니다.

```java
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import java.io.IOException;

public class KakaoAlimTalkSender {

    private static final String API_URL = "https://kakaoapi.url";  // 카카오 API URL
    private static final String API_KEY = "YOUR_API_KEY";  // 발급받은 API 키

    public static void main(String[] args) {
        sendAlimTalk("receiver_phone_number", "메시지 내용");
    }

    public static void sendAlimTalk(String receiverPhoneNumber, String messageContent) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(API_URL);

        // 헤더 설정
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setHeader("Authorization", "Bearer " + API_KEY);

        // JSON 바디 생성
        JSONObject json = new JSONObject();
        json.put("receiver_phone_number", receiverPhoneNumber);
        json.put("message", messageContent);

        // 요청 바디 설정
        try {
            StringEntity entity = new StringEntity(json.toString());
            httpPost.setEntity(entity);

            // 요청 실행
            CloseableHttpResponse response = httpClient.execute(httpPost);
            try {
                System.out.println(EntityUtils.toString(response.getEntity()));
            } finally {
                response.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
```

 

 


### 5. 응답 처리

알림톡 전송 요청에 대한 응답을 처리해야 합니다. 응답에는 메시지 전송 성공 여부 및 오류 코드 등이 포함됩니다. 이를 통해 메시지 전송 결과를 확인할 수 있습니다.

 

```java
public static void sendAlimTalk(String receiverPhoneNumber, String messageContent) {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(API_URL);

    // 헤더 설정
    httpPost.setHeader("Content-Type", "application/json");
    httpPost.setHeader("Authorization", "Bearer " + API_KEY);

    // JSON 바디 생성
    JSONObject json = new JSONObject();
    json.put("receiver_phone_number", receiverPhoneNumber);
    json.put("message", messageContent);

    // 요청 바디 설정
    try {
        StringEntity entity = new StringEntity(json.toString());
        httpPost.setEntity(entity);

        // 요청 실행
        CloseableHttpResponse response = httpClient.execute(httpPost);
        try {
            String responseString = EntityUtils.toString(response.getEntity());
            System.out.println(responseString);
            
            JSONObject jsonResponse = new JSONObject(responseString);
            int resultCode = jsonResponse.getInt("result_code");
            String resultMessage = jsonResponse.getString("result_message");

            if (resultCode == 0) {
                System.out.println("메시지 전송 성공: " + resultMessage);
            } else {
                System.out.println("메시지 전송 실패: " + resultMessage);
            }
        } finally {
            response.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            httpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
```

 


### 6. 에러 처리

API 호출 시 발생할 수 있는 다양한 에러를 처리해야 합니다. 예를 들어, 네트워크 문제, 인증 실패, 잘못된 요청 등의 상황에 대비해야 합니다. 이를 위해 try-catch 블록을 사용하여 예외를 처리합니다.

```java
public static void sendAlimTalk(String receiverPhoneNumber, String messageContent) {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(API_URL);

    // 헤더 설정
    httpPost.setHeader("Content-Type", "application/json");
    httpPost.setHeader("Authorization", "Bearer " + API_KEY);

    // JSON 바디 생성
    JSONObject json = new JSONObject();
    json.put("receiver_phone_number", receiverPhoneNumber);
    json.put("message", messageContent);

    // 요청 바디 설정
    try {
        StringEntity entity = new StringEntity(json.toString());
        httpPost.setEntity(entity);

        // 요청 실행
        CloseableHttpResponse response = httpClient.execute(httpPost);
        try {
            String responseString = EntityUtils.toString(response.getEntity());
            System.out.println(responseString);
            
            JSONObject jsonResponse = new JSONObject(responseString);
            int resultCode = jsonResponse.getInt("result_code");
            String resultMessage = jsonResponse.getString("result_message");

            if (resultCode == 0) {
                System.out.println("메시지 전송 성공: " + resultMessage);
            } else {
                System.out.println("메시지 전송 실패: " + resultMessage);
            }
        } finally {
            response.close();
        }
    } catch (IOException e) {
        System.err.println("네트워크 오류 발생: " + e.getMessage());
    } catch (JSONException e) {
        System.err.println("JSON 파싱 오류 발생: " + e.getMessage());
    } finally {
        try {
            httpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
```

 

반응형