회사 업무

[서버 개발] 서버 to 서버 통신

코드몬스터 2023. 8. 10. 09:27
728x90
💪 현재 작성하고 있는 중입니다.

 

일반적으로 통신이라고 하면 웹(클라이언트)에서 서버를 생각했었는데

업무를 하면서 서버와 서버 간의 통신하는 방법 몇 가지를 알게 되어 이를 정리해 보자고 한다.

 

서버 to 서버

서버끼리 http, https 통신을 할 수 있으며 통신 방법 코드는 여러 가지가 있다.

 

  1. HttpURLConnection && URLConnection
    두 클래스를 코드로 어떻게 작성되어 있는지 확인해보자.

HttpURLConnection 클래스

  • HttpURLConnection 클래스는 URLConnection 클래스를 상속(extends) 받으면서 추상화(abstract) 클래스 이다.
  • 생성자(Constructor)에서 protected 접근 제한자를 사용하면서 직접 인스턴스 생성이 불가능하다.
  • 생성자 안에 super를 사용하여 부모 멤버변수(필드) 값을 가져와서 사용한다.
    ⇒ 자신 클래스 멤버변수에 없어도 사용이 가능하다.
  • JDK에서 제공하는 클래스이다.
public abstract class HttpURLConnection extends URLConnection {

    // 생성자	
    protected HttpURLConnection (URL u) {
        super(u);
    }
}

 

 

URLConnection

  • 생성자(Constructor)에서 protected 접근 제한자를 사용하면서 직접 인스턴스 생성이 불가능하다.
public abstract class URLConnection {

    protected URL url;

    protected URLConnection(URL url) {
        this.url = url;
        if (url == null) {
            this.useCaches = defaultUseCaches;
        } else {
            this.useCaches = getDefaultUseCaches(url.getProtocol());
        }
    }
    
}

 

코드 작성 예시

import java.net.HttpURLConnection;
import java.net.URL;

public class TestClass() {
	
    public static void main (String[] args) {
    
        HttpURLConnection conn = null;
        InputStream = null;

        try {

            URL url = new URL("요청 보내는 주소");
            conn = (HttpURLConnection) url.openConnection();

            // 여러 가지 설정을 필요에 맞게 하면 된다.
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Context-Type", "text/json; charset=UTF-8");
            conn.setDoOutput(true);	// OutputStream으로 데이터 전달
            conn.setConnectionTimeout(10000)
            conn.connect();
            
            // 데이터 전달
            
            // 연결에 대한 결과
            int status = conn.getResponseCode();
            if (status == 200) {
                is = conn.getInputStream;
            } else {
                is = conn.getErrorStream;
            }

        } catch (Exception e) {
            // ... 이하 생략 ...
        }
    }
}

 

 

  1. RestTemplate

Synchronous client to perform HTTP requests, exposing a simple, template method API over underlying HTTP client libraries such as the JDK HttpURLConnection, Apache HttpComponents, and others. 

=> JDK HttpURLConnection, Apache HttpComponents 등과 같은 기본 HTTP 클라이언트 라이브러리를 통해 간단한 템플릿 메서드 API를 노출하여 HTTP 요청을 수행하는 동기 클라이언트입니다.

=> 스프링 프레임워크에서 제공하는 클래스이다.

생성자 요약

 

사용방법

 

 

참고 사이트

  1. https://blueyikim.tistory.com/2199 
  2. https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html