답변:
Java에서 간단한 SOAP 클라이언트를 구현하려면 SAAJ 프레임 워크 (JSE 1.6 이상과 함께 제공됨)를 사용할 수 있습니다.
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:
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;
}
}
<faultcode>soap:Client</faultcode><faultstring>Server did not recognize the value of HTTP Header SOAPAction: .</faultstring>
MimeHeaders headers = soapMessage.getMimeHeaders(); headers.addHeader("SOAPAction", "http://ws.cdyne.com/VerifyEmail");
. 나는 지금 그것이 그것 없이는 전에 작동했던 것이 이상하다고 생각합니다. :)
Map
of String
s로 만드시겠습니까?
예, WSDL 파일을 얻을 수 있다면 SoapUI를 사용하여 단위 테스트 요청으로 완성 된 해당 서비스의 모의 서비스를 만들 수 있습니다. 나는 당신이 시도 할 수 있음 (Maven을 사용)의 예를 만들었습니다 .
acdcjunior의 반응은 굉장했습니다. XML 요소를 반복하는 방법을 볼 수있는 다음 코드로 설명을 확장했습니다.
public class SOAPClientSAAJ {
public static void main(String args[]) throws Exception {
// Create SOAP Connection
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
// Send SOAP Message to SOAP Server
String url = "http://ws.cdyne.com/emailverify/Emailvernotestemail.asmx";
SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url);
SOAPPart soapPart=soapResponse.getSOAPPart();
// SOAP Envelope
SOAPEnvelope envelope=soapPart.getEnvelope();
SOAPBody soapBody = envelope.getBody();
@SuppressWarnings("unchecked")
Iterator<Node> itr=soapBody.getChildElements();
while (itr.hasNext()) {
Node node=(Node)itr.next();
if (node.getNodeType()==Node.ELEMENT_NODE) {
System.out.println("reading Node.ELEMENT_NODE");
Element ele=(Element)node;
System.out.println("Body childs : "+ele.getLocalName());
switch (ele.getNodeName()) {
case "VerifyEmailResponse":
NodeList statusNodeList = ele.getChildNodes();
for(int i=0;i<statusNodeList.getLength();i++){
Element emailResult = (Element) statusNodeList.item(i);
System.out.println("VerifyEmailResponse childs : "+emailResult.getLocalName());
switch (emailResult.getNodeName()) {
case "VerifyEmailResult":
NodeList emailResultList = emailResult.getChildNodes();
for(int j=0;j<emailResultList.getLength();j++){
Element emailResponse = (Element) emailResultList.item(j);
System.out.println("VerifyEmailResult childs : "+emailResponse.getLocalName());
switch (emailResponse.getNodeName()) {
case "ResponseText":
System.out.println(emailResponse.getTextContent());
break;
case "ResponseCode":
System.out.println(emailResponse.getTextContent());
break;
case "LastMailServer":
System.out.println(emailResponse.getTextContent());
break;
case "GoodEmail":
System.out.println(emailResponse.getTextContent());
default:
break;
}
}
break;
default:
break;
}
}
break;
default:
break;
}
} else if (node.getNodeType()==Node.TEXT_NODE) {
System.out.println("reading Node.TEXT_NODE");
//do nothing here most likely, as the response nearly never has mixed content type
//this is just for your reference
}
}
// print SOAP Response
System.out.println("Response SOAP Message:");
soapResponse.writeTo(System.out);
soapConnection.close();
}
private static SOAPMessage createSOAPRequest() throws Exception {
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
SOAPPart soapPart = soapMessage.getSOAPPart();
String serverURI = "http://ws.cdyne.com/";
// SOAP Envelope
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration("example", serverURI);
/*
Constructed SOAP Request Message:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:example="http://ws.cdyne.com/">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<example:VerifyEmail>
<example:email>mutantninja@gmail.com</example:email>
<example:LicenseKey>123</example:LicenseKey>
</example:VerifyEmail>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
*/
// SOAP Body
SOAPBody soapBody = envelope.getBody();
SOAPElement soapBodyElem = soapBody.addChildElement("VerifyEmail", "example");
SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("email", "example");
soapBodyElem1.addTextNode("mutantninja@gmail.com");
SOAPElement soapBodyElem2 = soapBodyElem.addChildElement("LicenseKey", "example");
soapBodyElem2.addTextNode("123");
MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("SOAPAction", serverURI + "VerifyEmail");
soapMessage.saveChanges();
/* Print the request message */
System.out.println("Request SOAP Message:");
soapMessage.writeTo(System.out);
System.out.println("");
System.out.println("------");
return soapMessage;
}
}
WSDL의 기본 인증의 경우 허용 된 응답 코드에서 오류가 발생합니다. 대신 다음을 시도하십시오.
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username","password".toCharArray());
}
});
String send =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n" +
" <soap:Body>\n" +
" </soap:Body>\n" +
"</soap:Envelope>";
private static String getResponse(String send) throws Exception {
String url = "https://api.comscore.com/KeyMeasures.asmx"; //endpoint
String result = "";
String username="user_name";
String password="pass_word";
String[] command = {"curl", "-u", username+":"+password ,"-X", "POST", "-H", "Content-Type: text/xml", "-d", send, url};
ProcessBuilder process = new ProcessBuilder(command);
Process p;
try {
p = process.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
StringBuilder builder = new StringBuilder();
String line = null;
while ( (line = reader.readLine()) != null) {
builder.append(line);
builder.append(System.getProperty("line.separator"));
}
result = builder.toString();
}
catch (IOException e)
{ System.out.print("error");
e.printStackTrace();
}
return result;
}