평상시 Restful 방식으로 Json 혹은 Text를 주고 받던중에 또 다른 웹서비스 방식중인 Soap 방식을 자바로 요청응답을 주고 받아야 하는일이 생겼습니다.

우선 Soap방식의 경우 XML을 요청 하고 응답을 받는데요.


오늘은 SOAPMessage를 이용한 XML을 요청 -> XML을 응답을 자바(Java)로 받는 과정을 포스팅을 하겠습니다.


SOAP (Simple Object Access Protocol) 이란?


SOAP은 HTTP, HTTPS, SMTP등을 사용하여 XML 기반의 메시지를 컴퓨터 네트워크 상에서 교환하는 형태의 프로토콜로써 웹 서비스(Web Service)의 기본적인 메시지 전송 수단이며 XML-RPC와 WDDX에서 envelope/header/body로 이루어진 구조와 전송(transport)과 상호 중립성(interaction neutrality)의 개념을 도입하였다. 

-> 쉽게말해 HTTP, HTTPS등 통신프로토콜 위에서 XML 메시지를 요청응답 받는것 입니다.



자바로 SOAP 요청/응답 하기 


먼저 부분 부분소스 분석을 한 뒤 하단에 풀소스를 첨부하겠습니다.

(급하신분들은 미리 맨하단 샘플소스를 참조해주시면되겠습니다.)


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
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();        
factory.setNamespaceAware(true);             
DocumentBuilder parser = factory.newDocumentBuilder();
 
//request SOAP message DOMSource create
String sendMessage = 
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
        "<root> " +
        "     <body>" +
        "         <record>" +
        "               ... " +
        "           ... " +
        "           ... " +
        "        </record>" + 
        "    <body>" +
        "</root> "
        
StringReader reader = new StringReader(sendMessage);
InputSource is = new InputSource(reader);
Document document = parser.parse(is);
DOMSource requestSource = new DOMSource(document);
 
//SOAPMessage create
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage requestSoapMessage = messageFactory.createMessage(); 
SOAPPart requestSoapPart = requestSoapMessage.getSOAPPart(); 
requestSoapPart.setContent(requestSource);
cs


세세한 설명보단 큰흐름만 집고 넘어가도록하겠습니다.

먼저 보낼(요청할) SOAP XML을 String으로 담고 MessageFactory, SOAPMessage등으로 요청할 XML로 파싱합니다.



1
2
3
4
5
6
//SOAPConnection create instance
SOAPConnectionFactory scf = SOAPConnectionFactory.newInstance();
SOAPConnection connection = scf.createConnection();
 
//SOAP SEND MESSAGE
SOAPMessage responseSoapMessage = connection.call(requestSoapMessage, "요청보낼 URL");
cs

요청할 SOAP XML을 생성한후, SOAPMessage를 요청할 연결준비를 합니다.

새로운 커넥션을 맺고 요청보낼 URL을 입력합니다.



1
2
3
4
5
6
7
8
9
10
11
12
ByteArrayOutputStream out = new ByteArrayOutputStream();
responseSoapMessage.writeTo(out);
                
SOAPBody soapBody = responseSoapMessage.getSOAPBody();  
Iterator i = soapBody.getChildElements();  
Node node = (Node) i.next();
          
JSONParser jsonParser = new JSONParser();
JSONObject soapResult = (JSONObject) jsonParser.parse(node.getChildNodes().item(0).getChildNodes().item(0).getNodeValue());
            
log.debug(soapResult.toString());
 
cs


*응답 XML안에 JSON값이 있을경우*

요청에 성공하였다면 responseSoapMessage 응답값을 OutputStream에 담고 만약 응답 SOAP XML내부에 JSON형식의 String이 있다면,

내부 Body노드를 찾아 JSON으로 파싱후 결과값을 출력 하면 됩니다.



1
2
3
4
5
6
ByteArrayOutputStream out = new ByteArrayOutputStream();
responseSoapMessage.writeTo(out);
 
String soapResult = new String(out.toByteArray(), "UTF-8");
 
log.debug(soapResult);
cs

*응답 XML을 찍어내고 싶은경우*

만약, JSON String이 아니라면 단순 응답값을 String으로 찍어낸후 확인하는 방법이 있습니다.


SAMPLE 소스 


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
import java.io.ByteArrayOutputStream;
import java.io.StringReader;
import java.util.Iterator;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.Node;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
 
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import javax.xml.transform.dom.DOMSource;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; 

try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();        
        factory.setNamespaceAware(true);             
        DocumentBuilder parser = factory.newDocumentBuilder();
 
        //request SOAP message DOMSource create
        String sendMessage = 
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
            "<root> " +
            "     <body>" +
            "         <record>" +
            "               ... " +
            "           ... " +
            "           ... " +
            "        </record>" + 
            "    <body>" +
            "</root> "
            
        StringReader reader = new StringReader(sendMessage);
        InputSource is = new InputSource(reader);
        Document document = parser.parse(is);
        DOMSource requestSource = new DOMSource(document);
 
        //SOAPMessage create
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage requestSoapMessage = messageFactory.createMessage(); 
        SOAPPart requestSoapPart = requestSoapMessage.getSOAPPart(); 
        requestSoapPart.setContent(requestSource);
 
        //SOAPConnection create instance
        SOAPConnectionFactory scf = SOAPConnectionFactory.newInstance();
        SOAPConnection connection = scf.createConnection();
 
        //SOAP SEND MESSAGE
        SOAPMessage responseSoapMessage = connection.call(requestSoapMessage, "요청보낼 URL");
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        responseSoapMessage.writeTo(out);
        //String soapResult = new String(out.toByteArray(), "UTF-8");
 
        SOAPBody soapBody = responseSoapMessage.getSOAPBody();  
 
        Iterator i = soapBody.getChildElements();  
        Node node = (Node) i.next();
          
        JSONParser jsonParser = new JSONParser();
        JSONObject soapResult = (JSONObject) jsonParser.parse(node.getChildNodes().item(0).getChildNodes().item(0).getNodeValue());
            
        log.debug(soapResult.toString());
 
catch (Exception e) {
    e.printStackTrace();
}       
cs

단순 import한 라이브러리, 클래스와 try/catch문 안의 핵심 소스만 첨부하였습니다.

샘플로만으로도 충분히 구현 할 수 있을 것입니다.


반응형

+ Recent posts