2013-10-10 2 views
27

자바를 통해 웹 서비스에 요청하는 방법에 대해 약간 혼란 스럽습니다.자바로 웹 서비스에 SOAP 요청하기

지금 내가 이해하는 유일한 점은 webservices가 xml 구조화 메시지를 사용하지만 여전히 요청을 구조화하는 방법을 이해하지 못했다는 것입니다.

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> 
    <soap:Body> 
    <getProductDetails xmlns="http://magazzino.example.com/ws"> 
     <productId>827635</productId> 
    </getProductDetails> 
    </soap:Body> 
</soap:Envelope> 

기본적으로 웹 서비스에 2 개의 매개 변수를 보내야하고 그 대신 두 개의 다른 매개 변수가 필요합니다.

대부분의 작업을 수행 할 수있는 항아리가 있지만 온라인을 찾지 못했습니다. 누군가 내게 그 근거를 설명해 줄 수 있습니까?

+1

wsdl 파일이 있으면 Java 클래스를 생성하여 대신 사용할 수 있습니다. – RandomQuestion

+0

[this stackoverflow topic] (http://stackoverflow.com/questions/19274828/how-to-use-wsdl/19276139#19276139)를보십시오. 나는 당신에게 유용 할 수있는 몇 가지 링크를 게시합니다. – Paolo

+1

예, 당신이 말하고있는 항아리는 혼자서 만들 수 있습니다. wsdport에서 javdocs를 찾아 클라이언트를 생성하십시오. 필요한 경우 항아리로 만들 수 있습니다.javadoc : http : //docs.oracle.com/javase/7/docs/technotes/tools/share/wsimport.html, 예 : http : //www.mkyong.com/webservices/jax-ws/jax-ws- wsimport-tool-example/ –

답변

63

SOAP 요청은 서버로 보내는 매개 변수로 구성된 XML 파일입니다.

SOAP 응답은 XML 파일이지만 이제는 서비스에서 제공하려는 모든 정보가 포함되어 있습니다.

기본적으로 WSDL은이 두 XML의 구조를 설명하는 XML 파일입니다.


자바 간단한 SOAP 클라이언트를 구현하려면, 당신은 SAAJ 프레임 워크를 사용할 수 있습니다 (위의 JSE 1.6과 함께 제공됩니다) :

SOAP를 첨부 파일 API와 자바 (SAAJ)에 대한입니다 주로 웹 서비스 API의 무대 뒤에서 발생하는 SOAP 요청/응답 메시지를 직접 처리하는 데 사용됩니다. 개발자는 JAX-WS를 사용하는 대신 비누 메시지를 직접 보내고받을 수 있습니다.

SAAJ를 사용하는 SOAP 웹 서비스 호출의 작동 예 (실행!)를 참조하십시오. 전화는 this web service입니다.

import javax.xml.soap.*; 

public class SOAPClientSAAJ { 

    // SAAJ - SOAP Client Testing 
    public static void main(String args[]) { 
     /* 
      The example below requests from the Web Service at: 
      http://www.webservicex.net/uszip.asmx?op=GetInfoByCity 


      To call other WS, change the parameters below, which are: 
      - the SOAP Endpoint URL (that is, where the service is responding from) 
      - the SOAP Action 

      Also change the contents of the method createSoapEnvelope() in this class. It constructs 
      the inner part of the SOAP envelope that is actually sent. 
     */ 
     String soapEndpointUrl = "http://www.webservicex.net/uszip.asmx"; 
     String soapAction = "http://www.webserviceX.NET/GetInfoByCity"; 

     callSoapWebService(soapEndpointUrl, soapAction); 
    } 

    private static void createSoapEnvelope(SOAPMessage soapMessage) throws SOAPException { 
     SOAPPart soapPart = soapMessage.getSOAPPart(); 

     String myNamespace = "myNamespace"; 
     String myNamespaceURI = "http://www.webserviceX.NET"; 

     // SOAP Envelope 
     SOAPEnvelope envelope = soapPart.getEnvelope(); 
     envelope.addNamespaceDeclaration(myNamespace, myNamespaceURI); 

      /* 
      Constructed SOAP Request Message: 
      <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:myNamespace="http://www.webserviceX.NET"> 
       <SOAP-ENV:Header/> 
       <SOAP-ENV:Body> 
        <myNamespace:GetInfoByCity> 
         <myNamespace:USCity>New York</myNamespace:USCity> 
        </myNamespace:GetInfoByCity> 
       </SOAP-ENV:Body> 
      </SOAP-ENV:Envelope> 
      */ 

     // SOAP Body 
     SOAPBody soapBody = envelope.getBody(); 
     SOAPElement soapBodyElem = soapBody.addChildElement("GetInfoByCity", myNamespace); 
     SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("USCity", myNamespace); 
     soapBodyElem1.addTextNode("New York"); 
    } 

    private static void callSoapWebService(String soapEndpointUrl, String soapAction) { 
     try { 
      // Create SOAP Connection 
      SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance(); 
      SOAPConnection soapConnection = soapConnectionFactory.createConnection(); 

      // Send SOAP Message to SOAP Server 
      SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(soapAction), soapEndpointUrl); 

      // Print the SOAP Response 
      System.out.println("Response SOAP Message:"); 
      soapResponse.writeTo(System.out); 
      System.out.println(); 

      soapConnection.close(); 
     } catch (Exception e) { 
      System.err.println("\nError occurred while sending SOAP Request to Server!\nMake sure you have the correct endpoint URL and SOAPAction!\n"); 
      e.printStackTrace(); 
     } 
    } 

    private static SOAPMessage createSOAPRequest(String soapAction) throws Exception { 
     MessageFactory messageFactory = MessageFactory.newInstance(); 
     SOAPMessage soapMessage = messageFactory.createMessage(); 

     createSoapEnvelope(soapMessage); 

     MimeHeaders headers = soapMessage.getMimeHeaders(); 
     headers.addHeader("SOAPAction", soapAction); 

     soapMessage.saveChanges(); 

     /* Print the request message, just for debugging purposes */ 
     System.out.println("Request SOAP Message:"); 
     soapMessage.writeTo(System.out); 
     System.out.println("\n"); 

     return soapMessage; 
    } 

} 
+2

완벽한 예입니다. 한 가지 질문은 xml 응답 결과를 읽는 기본 방법은 무엇입니까? 감사. –

+1

어떻게 기본 인증 세부 정보를 전달할 수 있습니까? – maamaa

+0

@maamaa http://stackoverflow.com/questions/17042259/java-saaj-basic-authentication은 어떻습니까? – acdcjunior

5

WSDL을 사용할 수있는 경우 해당 웹 서비스를 호출하기 위해 따라야 할 두 단계가 있습니다.

1 단계 : 더 보면

YourService service = new YourServiceLocator(); 
Stub stub = service.getYourStub(); 
stub.operation(); 

, 당신은 Stub 클래스에 사용되는 것을 알 수 있습니다 : 사용하여 작업을 호출하십시오 WSDL2Java 도구에서 클라이언트 측 소스

2 단계를 생성 원격 위치에 배포 된 서비스를 웹 서비스로 호출합니다. 이를 호출 할 때 클라이언트는 실제로 SOAP 요청을 생성하고 통신합니다. 마찬가지로 웹 서비스는 응답을 SOAP로 보냅니다. Wireshark와 같은 도구를 사용하면 교환 된 SOAP 메시지를 볼 수 있습니다.

기본 사항에 대한 자세한 설명을 요청 했으므로 here을 참조하고 클라이언트와 웹 서비스를 작성하여 자세히 알아 보시기 바랍니다.

관련 문제