SAAJ 예제 XML과 WebServices

이것은 SAAJ API를 이용해서 SOAP 메시지를 생성하고 전송하는 예제이다.

인벨롭과 헤더, 바디, 첨부, 폴트를 생성하고 내용을 출력한 뒤에 전송하는 과정이 모두 망라되어 있다.

XML 웹 서비스라는 책에 나온 예제를 조합하여 버그를 잡은 것이다.
이 책 내용은 상당히 알기 쉽다. 초보자가 웹 서비스를 이해하는데 도움이 될듯하고, 자바를 중심으로 씌여져 있다. 헌데, 오타가 좀 많고, 예제가 JWSDP 1.1기준이다. 현재 1.5가 나온 상황에서 안되는게 꽤 있는데, 그리 차이는 많이 나지 않는다.

지금 올리는 예제는 1.5에서 되는 것이다.

import javax.xml.soap.*;
import java.net.*;
import javax.activation.DataHandler;

public class SAAJTest {
    public static void main(String [] args) throws Exception {
        // SOAPMessage 객체 생성
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage requestMessage = messageFactory.createMessage();
        
        // SOAPPart 객체 생성
        SOAPPart soapPart = requestMessage.getSOAPPart();
        
        // SOAPEnvelope 객체 생성
        SOAPEnvelope envelope = soapPart.getEnvelope();
        
        // 네임스페이스 지정
        envelope.addNamespaceDeclaration("xsd", "http://www.w3.org/2001/XMLSchema");
        envelope.addNamespaceDeclaration("xsi", "http://www.w3.org/2001/XMLSchema-instance");
        envelope.addNamespaceDeclaration("enc", "http://www.w3.org/schemas.xmlsoap.org/soap/encoding/");
        envelope.addNamespaceDeclaration("ns0", "http://localhost:8080/hello/webservice/wsdl/webservice");
        
        // 인코딩 방식 지정
        envelope.setEncodingStyle("http://schemas.xmlsoap.org/soap/encoding/");
        
        // SOAPFactory 객체 생성
        SOAPFactory soapFactory = SOAPFactory.newInstance();
        
        // SOAPHeader 객체 얻기
        SOAPHeader header = envelope.getHeader();
        
        // 헤더 엔트리 생성
        Name name = soapFactory.createName(
                "authentication", "auth", "http://www.mincheol.com/auth");
        SOAPHeaderElement headerElement = header.addHeaderElement(name);
        headerElement.setActor("http://www.mincheol.com/auth");
        headerElement.setMustUnderstand(true);
        
        // 헤더 엔트리 자식 엘리먼트 생성
        name = soapFactory.createName("userid");
        SOAPElement useridElement = headerElement.addChildElement(name);
        useridElement.addTextNode("angel");
        
        // 헤더 엔트리 자식 엘리먼트 생성
        name = soapFactory.createName("password");
        SOAPElement passwordElement = headerElement.addChildElement(name);
        passwordElement.addTextNode("abc12345");
        
        // SOAPBody 객체 얻기
        SOAPBody body = envelope.getBody();
        
        // 바디 엔트리 생성
        
        // 이미 envelope에서 네임스페이스를 선언했으므로 마지막인자는 null 이다.
        Name bodyName = soapFactory.createName("sayHello", "ns0", null);
        SOAPBodyElement bodyElement = body.addBodyElement(bodyName);
        
        // 바디 엔트리 자식 엘리먼트 생성
        Name childName = soapFactory.createName("String_1");
        SOAPElement childElement = bodyElement.addChildElement(childName);
        Name typeName = soapFactory.createName("type", "xsi", null);
        childElement.addAttribute(typeName, "xsd:string");
        childElement.addTextNode("mincheol");
        
        // 첨부물 위치
        URL url = new URL("file:///home/kwon37xi/.vimrc");
        String contentId = "attached_image";
        // AttachmentPart 객체 얻기
        DataHandler dataHandler = new DataHandler(url);
        AttachmentPart attachment = requestMessage.createAttachmentPart(dataHandler);
        attachment.setContentId(contentId);
        // 요청 SOAP 메시지에 추가
        requestMessage.addAttachmentPart(attachment);
        
        // SOAPFault 객체 얻기
        SOAPFault fault = body.addFault();
        fault.setFaultCode(envelope.getPrefix() + ":Client"); // faultcode에는 접두사가필요하다.
        fault.setFaultActor("http://www.mincheol.com/auth");
        fault.setFaultString("Message does not have necessary info");
        Detail detail = fault.addDetail(); // detail 정보 생성
        Name entryName = soapFactory.createName("content"); // 네임스페이스 불필요
        DetailEntry entry = detail.addDetailEntry(entryName);
        entry.addTextNode("userid element does not have a value");
        
        // 지금까지 생성된 XML SOAP 메시지를 화면에 출력한다.
        System.out.println("-----------------------------------------------------");
        requestMessage.writeTo(System.out);
        System.out.println("-----------------------------------------------------");
        
        // SOAPConnection 객체생성
        SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
        SOAPConnection connection = soapConnectionFactory.createConnection();
        
        // 요청 SOAP 메시지를 보내고, 응답 SOAP 메시지를 받는다.
        SOAPMessage responseMessage = connection.call(requestMessage, 
                "http://localhost:9000/hello/webservice");
    }
}

공유하기 버튼

 
 

트랙백

이 글과 관련된 글 쓰기 (트랙백 보내기)
TrackbackURL : http://kwon37xi.egloos.com/tb/696462 [도움말]

덧글

댓글 입력 영역