본문 바로가기
IT, 개발/JAVA

JAVA - 자바에서 REST API 사용하기 예제 (GET, POST 방식)

by 개발자스터디 2022. 4. 8.
반응형

 

백엔드 개발자라면 무조건 사용할 수밖에 없는 REST API 기본적인 사용방법입니다.

 

GET방식과 POST방식 예제를 보면서 차이점을 확인하고 테스트해보도록 하겠습니다.

 

1. GET 방식 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
public void apiTestGet() throws Exception 
{
    URL url = null;
    String readLine = null;
    StringBuilder buffer = null;
    BufferedReader bufferedReader = null;
    BufferedWriter bufferedWriter = null;
    HttpURLConnection urlConnection = null;
        
    int connTimeout = 5000;
    int readTimeout = 3000;
        
    String apiUrl = "http://localhost:8080/api/test";    // 각자 상황에 맞는 IP & url 사용         
        
    try 
    {
        url = new URL(apiUrl);
        urlConnection = (HttpURLConnection)url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setConnectTimeout(connTimeout);
        urlConnection.setReadTimeout(readTimeout);
        urlConnection.setRequestProperty("Accept""application/json;");
            
        buffer = new StringBuilder();
        if(urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) 
        {
            bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(),"UTF-8"));
            while((readLine = bufferedReader.readLine()) != null
            {
                buffer.append(readLine).append("\n");
            }
        }
        else 
        {
            buffer.append("code : ");
            buffer.append(urlConnection.getResponseCode()).append("\n");
            buffer.append("message : ");
            buffer.append(urlConnection.getResponseMessage()).append("\n");
        }
    }
    catch(Exception ex) 
    {
        ex.printStackTrace();
    }
    finally 
    {
        try 
        {
            if (bufferedWriter != null) { bufferedWriter.close(); }
            if (bufferedReader != null) { bufferedReader.close(); }
        }
        catch(Exception ex) 
        { 
            ex.printStackTrace();
        }
    }
        
        
        System.out.println("결과 : " + buffer.toString());
    }
cs

 

 

2. POST 방식

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
public void apiTestPost() throws Exception 
{
    URL url = null;
    String readLine = null;
    StringBuilder buffer = null;
    OutputStream outputStream = null;
    BufferedReader bufferedReader = null;
    BufferedWriter bufferedWriter = null;
    HttpURLConnection urlConnection = null;
    
    int connTimeout = 5000;
    int readTimeout = 3000;
    
    String sendData = "보낼 데이터";                        // 대다수의 경우 JSON 데이터 사용  
    String apiUrl = "http://localhost:8080/api/test";    // 각자 상황에 맞는 IP & url 사용 
    
    try 
    {
        url = new URL(apiUrl);
        
        urlConnection = (HttpURLConnection)url.openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setConnectTimeout(connTimeout);
        urlConnection.setReadTimeout(readTimeout);
        urlConnection.setRequestProperty("Content-Type""application/json;");
        urlConnection.setDoOutput(true);
        urlConnection.setInstanceFollowRedirects(true);
        
        outputStream = urlConnection.getOutputStream();
        
        bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
        bufferedWriter.write(sendData);
        bufferedWriter.flush();
        
        buffer = new StringBuilder();
        if(urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) 
        {
            bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(),"UTF-8"));
            while((readLine = bufferedReader.readLine()) != null
            {
                buffer.append(readLine).append("\n");
            }
        }
        else 
        {
            buffer.append("\"code\" : \""+urlConnection.getResponseCode()+"\"");
            buffer.append(", \"message\" : \""+urlConnection.getResponseMessage()+"\"");
        }
    }
    catch(Exception ex) 
    {
        ex.printStackTrace();
    }
    finally 
    {
        try 
        {
            if (bufferedWriter != null) { bufferedWriter.close(); }
            if (outputStream != null) { outputStream.close(); }
            if (bufferedReader != null) { bufferedReader.close(); }
        }
        catch(Exception ex) 
        { 
            ex.printStackTrace();
        }
    }
    
    
    System.out.println("결과 : " + buffer.toString());
}
cs

 

각자 상황에 맞게 테스트 해보시기 바랍니다.

 

 

728x90
반응형