learn/web services

SOAP (Simple Object Access Protocol)

사겅이 2023. 9. 22. 02:48

SOAP (Simple Object Access Protocol)

 

출처 : https://www.linkedin.com/pulse/part-2-soap-web-services-sandeep-sahu/

 

 

웹 서비스 간의 통신을 위한 프로토콜
SOAP는 플랫폼 및 언어에 독립적이며, XML을 사용하여 데이터를 교환하는 기술
주로 웹 서비스에서 사용되며, 클라이언트와 서버 간의 표준화된 메시지 전달 방식을 제공

 

<Envelope>
<Header>...</Header>
<Body>...</Body>
<Fault>...</Fault>
</Envelope>
  • Envelope: 모든 SOAP 메시지의 최상위 요소로, 메시지를 감싸는 역할
  • Header: 선택적 요소로, 메시지의 부가적인 정보를 포함
  • Body: 메시지의 실제 데이터를 포함
  • Fault: 오류 발생 시 오류 정보를 포함
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPBodyElement;
import javax.xml.soap.SOAPConstants;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPFactory;
import javax.xml.soap.SOAPMessage;

public class SOAPExample {
    public static void main(String[] args) {
        try {
            // SOAP 메시지 생성
            MessageFactory factory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);
            SOAPMessage message = factory.createMessage();

            SOAPFactory soapFactory = SOAPFactory.newInstance();
            SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();

            // Header 생성 (선택적)
            // SOAPHeader header = envelope.getHeader();

            // Body 생성
            SOAPBody body = envelope.getBody();
            SOAPBodyElement element = body.addBodyElement(soapFactory.createName("HelloWorld"));
            element.addChildElement("Message").addTextNode("Hello, SOAP!");

            // SOAP 메시지 출력
            message.writeTo(System.out);
        } catch (SOAPException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

WSDL (Web Services Description Language)

웹 서비스의 기능, 메시지 형식, 프로토콜 등을 정의하는 XML 기반의 언어
클라이언트가 웹 서비스의 기능을 이해하고 요청

<?xml version="1.0"?>
<definitions xmlns="http://schemas.xmlsoap.org/wsdl/"
        xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
        xmlns:tns="http://example.com/stockquote.wsdl"
        targetNamespace="http://example.com/stockquote.wsdl">

<!-- Message 정의 -->
<message name="GetStockQuoteRequest">
<part name="ticker" type="string"/>
</message>

<message name="GetStockQuoteResponse">
<part name="price" type="float"/>
</message>

<!-- Port Type 정의 -->
<portType name="StockQuotePortType">
<operation name="GetStockQuote">
<input message="tns:GetStockQuoteRequest"/>
<output message="tns:GetStockQuoteResponse"/>
</operation>
</portType>

<!-- Binding 정의 -->
<binding name="StockQuoteSoapBinding" type="tns:StockQuotePortType">
<soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="GetStockQuote">
<soap:operation soapAction="http://example.com/stockquote/GetStockQuote"/>
<input>
<soap:body use="literal"/>
</input>
<output>
<soap:body use="literal"/>
</output>
</operation>
</binding>

<!-- Service 정의 -->
<service name="StockQuoteService">
<port name="StockQuotePort" binding="tns:StockQuoteSoapBinding">
<soap:address location="http://example.com/stockquote"/>
</port>
</service>
</definitions>
  • Types: 데이터 타입을 정의하는 섹션
  • Message: 웹 서비스가 주고 받는 메시지 형식을 정의
  • Port Type: 웹 서비스의 인터페이스를 정의
  • Binding: 메시지와 프로토콜을 연결하여 실제 통신을 정의
  • Service: 웹 서비스의 주소와 접근 가능한 동작을 정의
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import java.net.URL;

public class StockQuoteClient {
    public static void main(String[] args) {
        try {
            // WSDL 파일의 URL
            URL wsdlURL = new URL("http://example.com/stockquote.wsdl");

            // 서비스와 포트 이름 지정
            QName serviceName = new QName("http://example.com/stockquote.wsdl", "StockQuoteService");
            QName portName = new QName("http://example.com/stockquote.wsdl", "StockQuotePort");

            // 서비스 생성
            Service service = Service.create(wsdlURL, serviceName);

            // 서비스 인터페이스를 통해 원격 메서드 호출
            StockQuotePortType client = service.getPort(portName, StockQuotePortType.class);

            // 원격 메서드 호출
            GetStockQuoteRequest request = new GetStockQuoteRequest();
            request.setTicker("AAPL"); // 설정할 값에 따라 변경
            GetStockQuoteResponse response = client.GetStockQuote(request);

            // 결과 출력
            System.out.println("Stock Price: " + response.getPrice());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

UDDI (Ubiversal Description, Discovery, and Integration

출처 :&nbsp;https://www.informit.com/articles/article.aspx?p=31076&seqNum=3

 

웹 서비스를 등록, 검색 및 발견하기 위한 표준 프로토콜 및 레지스트리 시스템

 

  • UDDI 레지스트리: 웹 서비스 정보를 저장하고 검색하는 중앙 레지스트리
  • UDDI 클라이언트: 웹 서비스를 등록하고 검색하기 위한 응용 프로그램
import org.apache.juddi.api_v3.*;
import org.apache.juddi.v3.client.config.UDDIClerk;
import org.apache.juddi.v3.client.transport.TransportException;
import org.uddi.api_v3.*;
import org.uddi.v3_service.UDDIPublicationPortType;
import org.uddi.v3_service.UDDISecurityPortType;
import org.uddi.v3_service.UDDIInquiryPortType;

public class UDDIClientExample {

    public static void main(String[] args) throws Exception {
        // UDDI 서버 연결 설정
        UDDIClient uddiClient = new UDDIClient("META-INF/uddi.xml");
        UDDIClerk clerk = uddiClient.getClerk("default");

        try {
            // 엔터프라이즈의 비즈니스 정보 생성
            BusinessEntity myBusiness = new BusinessEntity();
            myBusiness.getName().add(new Name("My Business", null));
            myBusiness.setBusinessServices(new BusinessServices());
            BusinessService myService = new BusinessService();
            myService.getName().add(new Name("My Service", null));
            myService.setBusinessKey(clerk.register(myBusiness).getBusinessKey());
            clerk.register(myService);

            // 웹 서비스 정보 생성
            BindingTemplate myBindingTemplate = new BindingTemplate();
            myBindingTemplate.setAccessPoint(new AccessPoint("http://myservice.com", "endPoint"));
            myBindingTemplate.setServiceKey(myService.getServiceKey());
            clerk.register(myBindingTemplate);

            // 웹 서비스 검색
            UDDIInquiryPortType inquiry = uddiClient.getTransport("default").getUDDIInquiryService();
            FindService fs = new FindService();
            fs.setAuthInfo(clerk.getAuthToken());
            fs.getName().add(new Name("My Service", null));
            ServiceList foundServices = inquiry.findService(fs);
            if (foundServices.getServiceInfos() != null) {
                for (ServiceInfo serviceInfo : foundServices.getServiceInfos().getServiceInfo()) {
                    System.out.println("Found Service: " + serviceInfo.getName().get(0).getValue());
                }
            }
        } catch (TransportException e) {
            e.printStackTrace();
        }
    }
}

'learn > web services' 카테고리의 다른 글

REST API (Representational State Transfer API)  (0) 2023.09.22
Java Web Service AP  (0) 2023.09.22