ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 자바 URL 통신 사용법 및 총 정리
    Java 2023. 10. 12. 13:51

    자바를 사용해 URL통신 하는 방법

    import com.fasterxml.jackson.core.type.TypeReference;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import org.json.simple.JSONObject;
    import org.springframework.util.StringUtils;
    
    import javax.servlet.http.HttpServletResponse;
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.net.URLEncoder;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    public class LoginApi {
    
        public static String connectionUrl(String accessToken, String refreshToken
                                          , String connectionType, String role) throws Exception {
            try {
                final String API_DOMAIN = "http://127.0.0.1:8080";
                String path = "";
                String method = "";
                String result = "";
    
                if (!connectionType.equals("token") 
                && StringUtils.isEmpty(accessToken) 
                && StringUtils.isEmpty(refreshToken)) {
                    return "fail";
                }
    
                if (connectionType.equals("GET")) {
                    path = "/java/url/get";
                    method = "GET";
                } else {
                    path = "/java/url/post";
                    method = "POST";
                }
    
                String connectUrl = API_DOMAIN + path;
    
                /*
                모든 URL 클래스 객체의 생성자는 MalformedURLException예외를 throws 하여 
                예외처리에 대한 책임을 전가하고 있습니다.
                
                MalformedURLException은 생성자의 인자로 받은 url 문자열이 null이거나 
                프로토콜을 알 수 없을 때 등의 상황에 발생합니다. 
                
                따라서 URL 객체를 생성한 클래스에서 그 예외를 처리해주어야 합니다.
                 */
                // URL 객체 생성
                URL url = new URL(connectUrl);
    
                /*
                URL 클래스에 선언된 openConnection() 메소드는 url 객체에 대한 연결을 담당하는 
                URLConnection 객체를 반환합니다.
                
                HttpURLConnection 클래스는 HTTP 프로토콜 통신을 위한 클래스입니다.
                각각의 객체들은 하나의 요청을 위해 사용됩니다.
    
                위에서 URL 객체의 openConnection() 메소드를 통해 URLConnection 객체를 얻을 수 있었습니다. 
                HttpURLConnection객체는 URLConnection 객체를 확장하고(상속받고)있기 때문에 
                Type Casting을 통해 HttpURLConnection객체를 쉽게 얻을 수 있습니다.
                 */
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    
                /*  
                setRequestMethod() 메소드는 요청 메소드를 문자열 파라미터로 받아서 유효한 요청 메소드면 
                method 멤버 변수에 요청 메소드를 저장하고, 아니면 ProtocolException 예외를 발생시킵니다.
    
                method 멤버변수는 기본으로 "GET"으로 초기화되어있습니다. 
                따라서 setRequestMethod()를 통해 요청 메소드를 설정하지 않으면 GET 요청을 보내게 됩니다.
                */
                connection.setRequestMethod(method);
    
                // 접속이 지연될 때 timeout 처리
                // 시간은 millisecond 인데 1000 millisecond 가 1초이다.
                connection.setConnectTimeout(60000);
    
                /* 
                setRequestProperty() 메소드로 요청 헤더를 설정할 수 있습니다.
    
                setRequestProperty() 메소드는 String 타입의 key, value 파라미터를 받습니다. 
                만약 key값이 null이라면 NullPointerException 예외를 발생시킵니다.
                */
                connection.setRequestProperty("Content-Type", "application/json; utf-8");
                connection.setRequestProperty("Accept", "application/json");
                connection.setRequestProperty("client-id", "java_url_connection");
                connection.setRequestProperty("client-secret", "secret_key");
                if (connectionType.equals("GET")) {
                    String bearerAuth = "Bearer " + accessToken;
                    connection.setRequestProperty("Authorization", bearerAuth);
                }
    
                if (connectionType.equals("token")) {
                    // POST 요청을 할 때에는 OutputStream 객체로 데이터를 전송합니다.
                    // setDoOutput() 메소드를 통해 OutputStream 객체로 전송할 데이터가 있다는 옵션을 설정해야 합니다.
                    connection.setDoOutput(true);
                    JSONObject json = new JSONObject();
                    json.put("refreshToken", refreshToken);
                    String strJson = json.toString();
    
                    /*
                    getOutputStream() 메소드를 통해 연결에 사용할 OutputStream 객체를 얻을 수 있습니다.
                    프로토콜이 출력을 지원하지 않는다면 UnknownServiceException 예외를 발생시킵니다.
                    
                    getOutputSteam() 메소드를 통해 얻은 객체를 바로 넣어줄 수 있습니다.
                    */
                    try (OutputStream os = connection.getOutputStream()){
                        // 데이터를 byte로 변경 후 flush(), close() 진행
                        byte request_data[] = strJson.getBytes("utf-8");
                        os.write(request_data);
                        os.flush();
                        os.close();
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        throw ex;
                    }
                }
    
                // getResponseCode() 메소드를 통해 응답 코드를 얻을 수 있습니다. 정상적인 응답일 경우 200이 반환됩니다.
                int responseCode = connection.getResponseCode();
                if (responseCode == 200) {
                    // getInputStream() 메소드를 통해 응답 데이터를 읽을 수 있는 InputStream객체를 얻을 수 있습니다.
                    // 응답을 문자열 타입으로 얻기 위해 BufferedReader 객체를 사용할 수 있습니다.
                    BufferedReader bufferedReader 
                              = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
                    StringBuffer stringBuffer = new StringBuffer();
    
                    String inputLine = "";
                    // BufferedReader 객체를 읽은 후 String으로 전환하고 return값에 담아줍니다.
                    while ((inputLine = bufferedReader.readLine()) != null)  {
                        stringBuffer.append(inputLine);
                    }
                    bufferedReader.close();
                    
                    result = stringBuffer.toString();
                } else {
                    result = "fail";
                }
                return result;
    
            } catch (Exception e) {
                e.printStackTrace();
                throw e;
            }
    
        }
    
    }
Designed by Tistory.