2016-09-20 4 views
0

Хорошо, поэтому я абсолютно не знаком с веб-сервисами и проектом, над которым я работаю. Я пытаюсь обернуть голову вокруг всей вещи SOAP. Я думаю, что у меня есть смутное понимание того, что происходит, но у меня отсутствует какая-то конкретная информация, и я просто не могу найти что-нибудь полезное при поиске по Google.Отправка запроса SOAP на конкретную услугу

Я читал вопросы, заданные другим, как этот SOAP request to WebService with java, но я до сих пор не могу в полной мере выяснить, что происходит.

Конкретно я пытаюсь использовать услуги, предоставляемые здесь http://ec.europa.eu/taxation_customs/vies/vatRequest.html с файлом WSDL здесь http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl

Я попытался адаптировать пример, приведенный в выше вопросе, но я просто не могу понять, какие ценности для добавления где поэтому он работает с этой конкретной услугой. Все, что я получаю, это ответ «405 Метод не допускается». Вот моя попытка адаптации:

package at.kmds.soaptest; 

import javax.xml.soap.*; 
import javax.xml.transform.Source; 
import javax.xml.transform.Transformer; 
import javax.xml.transform.TransformerFactory; 
import javax.xml.transform.stream.StreamResult; 

public class Main { 
    public static void main(String args[]) { 
     try { 
      // Create SOAP Connection 
      SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance(); 
      SOAPConnection soapConnection = soapConnectionFactory.createConnection(); 

      // Send SOAP Message to SOAP Server 
      String url = "http://ec.europa.eu/taxation_customs/vies/vatRequest.html"; 
      SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url); 

      // Process the SOAP Response 
      printSOAPResponse(soapResponse); 

      soapConnection.close(); 
     } catch (Exception e) { 
      System.err.println("Error occurred while sending SOAP Request to Server"); 
      e.printStackTrace(); 
     } 
    } 

    private static SOAPMessage createSOAPRequest() throws Exception { 
     MessageFactory messageFactory = MessageFactory.newInstance(); 
     SOAPMessage soapMessage = messageFactory.createMessage(); 
     SOAPPart soapPart = soapMessage.getSOAPPart(); 

     String serverURI = "http://ec.europa.eu/"; 

     // SOAP Envelope 
     SOAPEnvelope envelope = soapPart.getEnvelope(); 
     envelope.addNamespaceDeclaration("example", serverURI); 

     // SOAP Body 
     SOAPBody soapBody = envelope.getBody(); 
     SOAPElement soapBodyElem = soapBody.addChildElement("checkVat"); 
     SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("countryCode"); 
     soapBodyElem1.addTextNode("..."); 
     SOAPElement soapBodyElem2 = soapBodyElem.addChildElement("vatNumber"); 
     soapBodyElem2.addTextNode("..."); 

     MimeHeaders headers = soapMessage.getMimeHeaders(); 
     headers.addHeader("SOAPAction", serverURI + "checkVat"); 

     soapMessage.saveChanges(); 

     /* Print the request message */ 
     System.out.print("Request SOAP Message = "); 
     soapMessage.writeTo(System.out); 
     System.out.println(); 

     return soapMessage; 
    } 

    private static void printSOAPResponse(SOAPMessage soapResponse) throws Exception { 
     TransformerFactory transformerFactory = TransformerFactory.newInstance(); 
     Transformer transformer = transformerFactory.newTransformer(); 
     Source sourceContent = soapResponse.getSOAPPart().getContent(); 
     System.out.print("\nResponse SOAP Message = "); 
     StreamResult result = new StreamResult(System.out); 
     transformer.transform(sourceContent, result); 
    } 
} 

Если кто-то может объяснить мне, что именно я делаю не так и как это исправить, или, может быть, даже дать мне рабочий пример, я бы бесконечно благодарен ...

ответ

1

Код должен быть слегка изменен, чтобы попасть в сервис.

String url = "http://ec.europa.eu/taxation_customs/vies/services/checkVatService"; 

является конечной точкой вы должны ударить (это из WSDL)

<wsdlsoap:address location="http://ec.europa.eu/taxation_customs/vies/services/checkVatService"/> 

Обратите внимание, что, когда я ударил этого, я получаю мыло fault.Looks как на SOAPBody сконструированного должен быть снова проверили.

Request SOAP Message = <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:example="http://ec.europa.eu/"><SOAP-ENV:Header/><SOAP-ENV:Body><checkVat><countryCode>...</countryCode><vatNumber>...</vatNumber></checkVat></SOAP-ENV:Body></SOAP-ENV:Envelope> 

Response SOAP Message = <?xml version="1.0" encoding="UTF-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><soap:Fault><faultcode>soap:Client</faultcode><faultstring>Unexpected wrapper element checkVat found. Expected {urn:ec.europa.eu:taxud:vies:services:checkVat:types}checkVat.</faultstring></soap:Fault></soap:Body></soap:Envelope> 

Edit полная программа, которая работает (похоже), дает мне неверный ввод, потому что я передаю точки (...).

import javax.xml.namespace.QName; 
import javax.xml.soap.*; 
import javax.xml.transform.Source; 
import javax.xml.transform.Transformer; 
import javax.xml.transform.TransformerFactory; 
import javax.xml.transform.stream.StreamResult; 

public class Main { 
    public static void main(String args[]) { 
     try { 
      // Create SOAP Connection 
      SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance(); 
      SOAPConnection soapConnection = soapConnectionFactory.createConnection(); 

      // Send SOAP Message to SOAP Server 
      String url = "http://ec.europa.eu/taxation_customs/vies/services/checkVatService"; 
      SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url); 

      // Process the SOAP Response 
      printSOAPResponse(soapResponse); 

      soapConnection.close(); 
     } catch (Exception e) { 
      System.err.println("Error occurred while sending SOAP Request to Server"); 
      e.printStackTrace(); 
     } 
    } 

    private static SOAPMessage createSOAPRequest() throws Exception { 
     MessageFactory messageFactory = MessageFactory.newInstance(); 
     SOAPMessage soapMessage = messageFactory.createMessage(); 
     SOAPPart soapPart = soapMessage.getSOAPPart(); 

     String serverURI = "http://ec.europa.eu/"; 

     // SOAP Envelope 
     SOAPEnvelope envelope = soapPart.getEnvelope(); 
     envelope.addNamespaceDeclaration("tns1", "urn:ec.europa.eu:taxud:vies:services:checkVat:types"); 
     envelope.addNamespaceDeclaration("impl", "urn:ec.europa.eu:taxud:vies:services:checkVat"); 

     // SOAP Body 
     SOAPBody soapBody = envelope.getBody(); 
     QName bodyQName = new QName("urn:ec.europa.eu:taxud:vies:services:checkVat:types", 
       "checkVat", "tns1"); 
     SOAPElement soapBodyElem = soapBody.addChildElement(bodyQName); 

     SOAPElement soapBodyElem1 = soapBodyElem.addChildElement(new QName("urn:ec.europa.eu:taxud:vies:services:checkVat:types", 
       "countryCode", "tns1")); 
     soapBodyElem1.addTextNode("..."); 
     SOAPElement soapBodyElem2 = soapBodyElem.addChildElement(new QName("urn:ec.europa.eu:taxud:vies:services:checkVat:types", 
       "vatNumber", "tns1")); 
     soapBodyElem2.addTextNode("..."); 

     MimeHeaders headers = soapMessage.getMimeHeaders(); 
     headers.addHeader("SOAPAction", serverURI + "checkVat"); 

     soapMessage.saveChanges(); 

     /* Print the request message */ 
     System.out.print("Request SOAP Message = "); 
     soapMessage.writeTo(System.out); 
     System.out.println(); 

     return soapMessage; 
    } 

    private static void printSOAPResponse(SOAPMessage soapResponse) throws Exception { 
     TransformerFactory transformerFactory = TransformerFactory.newInstance(); 
     Transformer transformer = transformerFactory.newTransformer(); 
     Source sourceContent = soapResponse.getSOAPPart().getContent(); 
     System.out.print("\nResponse SOAP Message = "); 
     StreamResult result = new StreamResult(System.out); 
     transformer.transform(sourceContent, result); 
    } 
} 

Придает назад

<?xml version="1.0" encoding="UTF-8"?> 
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> 
    <soap:Body> 
     <soap:Fault> 
     <faultcode>soap:Server</faultcode> 
     <faultstring>INVALID_INPUT</faultstring> 
     </soap:Fault> 
    </soap:Body> 
</soap:Envelope> 
+0

Спасибо так много, он работает сейчас! Считаете ли вы, что вы можете быть добры к ELI5, как вы знали, какие ценности использовать где? Или вы знаете учебник, который объясняет это? Я никогда бы не нашел это сам ... – Szernex

+1

Рад, что это помогло. Я просто отослал https://docs.oracle.com/cd/E19879-01/819-3669/bnbhw/index.html. Я в основном копирую ваш код. Я обнаружил, что пространство имен неверно, создавая образец SOAP-запроса для инструментария SOAP UI. Я понял, что пространство имен необходимо добавить, я просто сделал это. –

+0

Хорошо, я посмотрю на это, еще раз спасибо! – Szernex

Смежные вопросы