IT

Java 클래스에서 SOAP 웹 서비스 호출을 수행하는 방법은 무엇입니까?

lottoking 2020. 8. 5. 07:40
반응형

Java 클래스에서 SOAP 웹 서비스 호출을 수행하는 방법은 무엇입니까?


나는 웹 서비스 세계에 익숙하지 않고 내 연구가 나를 깨우치는 것보다 더 혼란스럽게하는 것입니다. 제 문제는 웹 서비스 기능으로 확장해야하는 라이브러리 (jar)를 받았다는 것입니다.

이 라이브러리는 다른 개발자와 공유하고 jar의 클래스 중 하나는 웹 서비스를 호출하는 메소드가있는 클래스입니다 (기본적으로 클래스의 속성을 설정하고 객체를 db에 저장하는 것과 같은 일부 비즈니스를 수행함) 수정 한 개체를 다시 보냅니다. 클래스를 사용하는 개발자가 할 필요가있는 간편한 한 간단하고 간단하게 서비스를 호출하고 싶습니다.

Car c = new Car("Blue");
c.webmethod();

서버에서 사용하기 위해 JAX-WS를 연구했지만 wsimport서버와 wsimport클라이언트 에서 서버 를 만들 필요가없는 것입니다. 둘 다 클래스가 있기 때문에 클래스 간 상호 작용이 필요합니다. 서버와 클라이언트 모두에서 공유됩니다. 수업 중에 웹 서비스와 전화를하는 것이 어떻게 합리적이라고 생각하십니까?


귀하의 문제 가 Java에서 SOAP (JAX-WS) 웹 서비스를 호출하고 반환하는 것을 얻는 방법으로 귀결 짜증나는 것을 이해합니다 . 이 경우 가능한 두 가지 접근 방식이 있습니다.

  1. wsimport이를 통해 Java 클래스를 생성 하고 사용하십시오. 또는
  2. 다음과 같은 SOAP 클라이언트를 작성하십시오.
    1. 서비스 매개 변수를 XML로 구성 화합니다.
    2. HTTP 조작을 통해 웹 메소드를 호출합니다.
    3. 리턴되는 XML 응답을 다시 오브젝트로 구문 분석하십시오.


첫 번째 접근 방법 (사용 wsimport) :

서비스 (엔티티 또는 기타) 비즈니스 클래스가 이미있는 것을 보았습니다.이 클래스 wsimport는 완전히 새로운 클래스 세트를 생성 하는 사실입니다 (이미 이미있는 클래스와 해당됩니다).

그러나이 시나리오에서는 다음 중 하나만 수행 할 수 있습니다.

  • 적응 (편집) wsimport코드가 사용하기 위해 귀하의 비즈니스 클래스를 사용하기 위해 사용하기 위해 귀하의 비즈니스 클래스 (이없는 가치가 어떻게 처리해야할까요?-WSDL에 변경, 당신은 다시 생성하고 코드를 재 적응할 필요가 없습니다); 또는
  • wsimport생성 된 클래스를 포기하고 사용하십시오 . 이 솔루션에서 비즈니스 코드는 생성 된 클래스를 다른 아키텍처 계층의 서비스로 "사용"할 수 있습니다.

두 번째 방법 정보 (사용자 정의 SOAP 클라이언트 작성) :

두 번째 접근 방식을 구현하려면 다음을 수행해야합니다.

  1. 전화 걸기 :
    • SAAJ (SOAP with Attachments API for Java) 프레임 워크 (아래 참조, Java SE 1.6 이상과 함께 제공됨)를 사용하여 호출하십시오. 또는
    • 당신은 또한 그것을 통해 java.net.HttpUrlconnection(그리고 일부 java.io처리) 할 수 있습니다 .
  2. XML로 수업을 받고받습니다.
    • JAXB와 같은 OXM (Object to XML Mapping) 프레임 워크를 사용하여 XML을 생성 화 / 생성 화
    • 또는 필요한 경우 XML을 수동으로 생성 / 파싱합니다 (수신 된 객체가 전송 된 객체와 약간 다른 경우 가장 좋은 솔루션이 될 수 있습니다).

클래식을 사용하여 SOAP 클라이언트를 작성하는 java.net.HttpUrlConnection것은 그리 어렵지 않습니다. 이 링크 에서 아주 좋은 시작 코드를 사용할 수 있습니다 .

SAAJ 프레임 워크를 사용하는 것이 좋습니다.

SAAJ (SOAP with Attachments API for Java) 는 주로 모든 웹 서비스 API에서 발생하는 SOAP 요청 / 응답 메시지를 직접 처리하는 데 사용됩니다. 개발자가 JAX-WS를 사용하는 대신 SOAP 메시지를 직접받을 수 있습니다.

SAAJ를 사용하여 SOAP 웹 서비스 호출의 실제 예제 (실행하십시오!)를 참조하십시오. 이 웹 서비스를 호출 합니다 .

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:
             https://www.w3schools.com/xml/tempconvert.asmx?op=CelsiusToFahrenheit


            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 = "https://www.w3schools.com/xml/tempconvert.asmx";
        String soapAction = "https://www.w3schools.com/xml/CelsiusToFahrenheit";

        callSoapWebService(soapEndpointUrl, soapAction);
    }

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

        String myNamespace = "myNamespace";
        String myNamespaceURI = "https://www.w3schools.com/xml/";

        // 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="https://www.w3schools.com/xml/">
                <SOAP-ENV:Header/>
                <SOAP-ENV:Body>
                    <myNamespace:CelsiusToFahrenheit>
                        <myNamespace:Celsius>100</myNamespace:Celsius>
                    </myNamespace:CelsiusToFahrenheit>
                </SOAP-ENV:Body>
            </SOAP-ENV:Envelope>
            */

        // SOAP Body
        SOAPBody soapBody = envelope.getBody();
        SOAPElement soapBodyElem = soapBody.addChildElement("CelsiusToFahrenheit", myNamespace);
        SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("Celsius", myNamespace);
        soapBodyElem1.addTextNode("100");
    }

    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;
    }

}

통합화 / 역화에 JAXB를 사용하는 방법에 대한 정보를 쉽게 사용할 수 있습니다. 당신은 여기에서 시작할 수 있습니다. http://www.mkyong.com/java/jaxb-hello-world-example/를 .


또는 Apache CXF의 wsdl2java 를 사용하여 사용할 수있는 클래스를 생성하십시오.

웹 사이트에서 다운로드 할 수있는 바이너리 패키지에 포함되어 있습니다. 다음과 같은 명령을 간단히 사용할 수 있습니다.

$ ./wsdl2java -p com.mynamespace.for.the.api.objects -autoNameResolution http://www.someurl.com/DefaultWebService?wsdl

그것은 당신처럼 사용할 수있는 객체를 생성하기 위해 WSDL을 사용하여 (당신은 다른의 약간 수 있도록 개체 이름은 또한 WSDL에서 잡고있다)

DefaultWebService defaultWebService = new DefaultWebService();
String res = defaultWebService.getDefaultWebServiceHttpSoap11Endpoint().login("webservice","dadsadasdasd");
System.out.println(res);

소스를 생성하는 Maven 플러그인도 있습니다 : https://cxf.apache.org/docs/maven-cxf-codegen-plugin-wsdl-to-java.html

참고 : CXF 및 IDEA를 사용하여 소스를 생성하는 경우 https://stackoverflow.com/a/46812593/840315 를 살펴볼 수 있습니다.


비누 메시지를 생성하는 훨씬 더 간단한 대안을 찾았습니다. Person 객체가 주어지면 :

import com.fasterxml.jackson.annotation.JsonInclude;

@JsonInclude(JsonInclude.Include.NON_NULL)
public class Person {
  private String name;
  private int age;
  private String address; //setter and getters below
}

다음은 간단한 Soap 메시지 생성기입니다.

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

@Slf4j
public class SoapGenerator {

  protected static final ObjectMapper XML_MAPPER = new XmlMapper()
      .enable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL)
      .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
      .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
      .registerModule(new JavaTimeModule());

  private static final String SOAP_BODY_OPEN = "<soap:Body>";
  private static final String SOAP_BODY_CLOSE = "</soap:Body>";
  private static final String SOAP_ENVELOPE_OPEN = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">";
  private static final String SOAP_ENVELOPE_CLOSE = "</soap:Envelope>";

  public static String soapWrap(String xml) {
    return SOAP_ENVELOPE_OPEN + SOAP_BODY_OPEN + xml + SOAP_BODY_CLOSE + SOAP_ENVELOPE_CLOSE;
  }

  public static String soapUnwrap(String xml) {
    return StringUtils.substringBetween(xml, SOAP_BODY_OPEN, SOAP_BODY_CLOSE);
  }
}

다음과 같이 사용할 수 있습니다.

 public static void main(String[] args) throws Exception{
        Person p = new Person();
        p.setName("Test");
        p.setAge(12);

        String xml = SoapGenerator.soapWrap(XML_MAPPER.writeValueAsString(p));
        log.info("Generated String");
        log.info(xml);
      }

참고 URL : https://stackoverflow.com/questions/15940234/how-to-do-a-soap-web-service-call-from-java-class

반응형