Http client POST request xml+soap - scala

I want to make a post request in Scala to this API http://api.atinternet-solutions.com/toolbox/reporting.asmx
I first did it with a curl like this :
curl -X POST -T post.txt -H "Content-Type: application/soap+xml; charset=utf-8" http://api.atinternet-solutions.com/toolbox/reporting.asmx -v
and I got what I expected.
Now I want to call the API programatically with a simple HttpClient
val httpClient = new DefaultHttpClient()
def postRequest=new HttpPost("https://api.atinternet-solutions.com/toolbox/reporting.asmx")
postRequest.addHeader("Content-Type","application/soap+xml ; charset=utf-8")
postRequest.addHeader("SOAPAction","\"http://www.xiti.com/queryReport\"")
val file=new File("post.txt")
val fe=new FileEntity(file,"application/soap+xml;charset=utf-8")
postRequest.setEntity(fe)
val httpResponse=httpClient.execute(postRequest)
println(httpResponse.getStatusLine.toString)
val rspStr=Source.createBufferedSource(httpResponse.getEntity.getContent).mkString
println(rspStr)
but I get an HTTP/1.1 500 Internal Server Error
and printing the rspStr yields
"?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><soap:Fault><soap:Code><soap:Value>soap:Receiver</soap:Value></soap:Code><soap:Reason><soap:Text xml:lang="en">Server was unable to process request. ---> Root element is missing.</soap:Text></soap:Reason><soap:Detail /></soap:Fault></soap:Body></soap:Envelope"
The post.txt looks like below, except I set the good information instead.
<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
<soap12:Header>
<NXHeader xmlns="http://www.xiti.com/">
<GUID>string</GUID>
<SecurityKey>string</SecurityKey>
<Site>int</Site>
</NXHeader>
</soap12:Header>
<soap12:Body>
<queryReport xmlns="http://www.xiti.com/">
<startDate>int</startDate>
<endDate>int</endDate>
<query>string</query>
<param>string</param>
<typereport>XML or CSV</typereport>
</queryReport>
</soap12:Body>
</soap12:Envelope>
The curl action which is working is done from my scala project directory. I printed post.txt in scala and got the good content.
I cannot figure out what is going wrong. Thank you for your help

I tried your call with the dispatch library.
This is my code
import dispatch._
import java.io.File
object ToolBox {
val endpoint = url("https://api.atinternet-solutions.com/toolbox/reporting.asmx").POST
.addHeader("Content-Type","application/soap+xml ; charset=utf-8")
.addHeader("SOAPAction",""" "http://www.xiti.com/queryReport" """)
def report = Http( endpoint <<< new File("post.txt") > as.xml.Elem)
def tryReport = {
val res = report.either
for {
ex <- res.left
} yield "Something got wrong " + ex.getMessage
}
}
The service replies with a status 500 like you, but the faultString in the response xml is: A parameter is missing in your NXHeader or you have a namespace issue.
Is it what you would expect, since the post.txt body contains only the placeholders from the query report example, instead of real parameters?

I found what was going wrong.
Replace
def postRequest
by
val postRequest.
Tks again

Related

parsing soap response using Cypress

Facing issues while parsing this response using cypress,
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Header/>
<soapenv:Body>
<p385:summaryOutputArray xmlns:p385="http://dataobject.simulation.com">
<p385:userName>MS</p385:userName>
</p385:summaryOutputArray>
</soapenv:Body>
</soapenv:Envelope>
Using Cypress How to read userName TAG? I can see in the log that whole xml is printed but can't get to the particular tag. Also, while using the function to get to the particular tag to get the value, I am getting null property
Firstly I used this. This is giving error. property reading null
const parser = new DOMParser();
const xmlDOM = parser.parseFromString(quoteResp, 'text/xml');
cy.log('xmlDOM ' + quoteResp.);
cy.wrap(Cypress.$(quoteResp)).then(quoteResp => {
const txt = quoteResp.filter('Body').find('p385:userName').text();
cy.log('value:' + txt);
});
Using this I can see the whole response in logs
then(quoteResp => {cy.log('xmlDOM ' + quoteResp.body);
It's not necessary to wrap the response, just query the xmlDOM like this
const xmlDOM = parser.parseFromString(quoteResp, 'application/xml');
const userName = xmlDOM.querySelector('userName').textContent
expect(userName).to.eq('MS')

Printing SOAP response in Karate DSL

I have this feature file and i get a response correctly. I want to print obtained value from response but somehow I am not able to do that. Tried to research some stuff but I couldnt help myself.
Can anyone help please? Thanks in advance
Feature:
test of soap
Background:
* url 'http://www.dataaccess.com/webservicesserver/numberconversion.wso'
Scenario: soap 1.1
Given request
"""
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://www.dataaccess.com/webservicesserver/">
<soapenv:Header/>
<soapenv:Body>
<web:NumberToDollars>
<web:dNum>10</web:dNum>
</web:NumberToDollars>
</soapenv:Body>
</soapenv:Envelope>
"""
When soap action 'Conversion'
Then status 200
* print '\n', response
#working
* match response /Envelope/Body/NumberToDollarsResponse/NumberToDollarsResult == 'ten dollars'
#not working
* print response.Envelope.Body.NumberToDollarsResponse.NumberToDollarsResult
#not working
* print response /Envelope/Body/NumberToDollarsResponse/NumberToDollarsResult
#not working
* def x = response /Envelope/Body/NumberToDollarsResponse/NumberToDollarsResult
* print x
If you read the docs, print only handles JS on the right-hand-side, not XPath.
For what you want, please do in 2 steps:
* def temp = /Envelope/Body/NumberToDollarsResponse/NumberToDollarsResult
* print temp

Gatling extract xpath values error "Namespace prefix 'soap' has not been declared"

Below scenario bringing in me proper SOAP body but I'm not able to extract it's values using xpath expression
The path expression /*/soap:Body/m:NumberToDollarsResponse/m:NumberToDollarsResult/text() I have formed using this website
https://codebeautify.org/Xpath-Tester
val httpConf = http.baseUrl("https://www.dataaccess.com")
val headerXml = Map("Keep-Alive" -> "115", "Content-Type" -> "application/soap+xml; charset=utf-8")
val soapXmlScn = scenario("make First Soap Call")
.exec(
http("Soap API Call With XML")
.post("/webservicesserver/numberconversion.wso")
.headers(headerXml)
.body(StringBody("""<?xml version="1.0" encoding="utf-8"?>
<soap20:Envelope xmlns:soap20="http://www.w3.org/2003/05/soap-envelope">
<soap20:Body>
<NumberToDollars xmlns="http://www.dataaccess.com/webservicesserver/">
<dNum>45</dNum>
</NumberToDollars>
</soap20:Body>
</soap20:Envelope>"""))
.check(status.is(200))
.check(xpath("""//*/soap:Body/m:NumberToDollarsResponse/m:NumberToDollarsResult/text()""").saveAs("doller_value" ))
)
.exec {
session =>
println("doller value >>>> " + session("doller_value").as[String].toString)
session
}
Response body is
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
<soap:Body>
<m:NumberToDollarsResponse xmlns:m="http://www.dataaccess.com/webservicesserver/">
<m:NumberToDollarsResult>forty five dollars</m:NumberToDollarsResult>
</m:NumberToDollarsResponse>
</soap:Body>
</soap:Envelope>
The error shown on console is
12:22:16.880 [ERROR] i.g.c.a.b.SessionHookBuilder$$anon$1 - 'hook-1' crashed with 'j.u.NoSuchElementException: No attribute named 'doller_value' is defined', forwarding to the next one
namespace List needs to be provided to your xpath check as below and my request working fine. Those namespace URLs are mentioned in your SOAP response xml only
.check(xpath("""//soap:Envelope/soap:Body/m:NumberToDollarsResponse/m:NumberToDollarsResult/text()""", List("soap" -> "http://www.w3.org/2003/05/soap-envelope", "m" -> "http://www.dataaccess.com/webservicesserver/")).findAll.saveAs("doller_value" ))

Need help recreating a SOAP request in groovy-wslite

I had issues getting the most basic of actions working, but finally figured it out. You can see what I did here
With that working I'm moving onto the subsequent action and once again running into issues. Here is what the XML SOAP Request looks like which works (generated in PHP)
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="urn:ws.company.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns2="ws.company.com">
<SOAP-ENV:Header>
<ns2:SessionHeader>
<ns2:sessionId>theLoginSessionID</ns2:sessionId>
</ns2:SessionHeader>
</SOAP-ENV:Header>
<SOAP-ENV:Body>
<ns1:triggerCampaignMessage>
<ns1:campaign>
<ns1:folderName>theFolder</ns1:folderName>
<ns1:objectName>theObject</ns1:objectName>
</ns1:campaign>
<ns1:recipientData>
<ns1:recipient>
<ns1:listName>
<ns1:folderName>theFolder</ns1:folderName>
<ns1:objectName>theObject</ns1:objectName>
</ns1:listName>
<ns1:emailAddress>person#company.com</ns1:emailAddress>
</ns1:recipient>
<ns1:optionalData>
<ns1:name>order_number</ns1:name>
<ns1:value>231</ns1:value>
</ns1:optionalData>
</ns1:recipientData>
</ns1:triggerCampaignMessage>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
The code I am trying to use is this
#Grab(group='com.github.groovy-wslite', module='groovy-wslite', version='0.8.0')
import wslite.soap.*
def client = new SOAPClient('https://company/services/WebService')
def response = client.send(SOAPAction:'https://company/services/WebService/') {
body {
login('xmlns':'urn:ws.company.com') {[
username("username"),
password("password")
]}
}
}
theSession = response.envelope
try {
response = client.send(SOAPAction:'https://company/services/WebService/') {
header {
SessionHeader('xmlns':'urn:ws.company.com') {
sessionId(theSession)
}
}
body {
triggerCampaignMessage('xmlns':'urn:ws.company.com') {[
campaign {[
folderName("theFolder"),
objectName("theObject")
]},
recipientData {[
recipient {[
listName {[
folderName("theFolder"),
objectName("theObject")
]},
emailAddress("person#company.com")
]},
optionalData {[
name("order_number"),
value("1234567890")
]}
]}
]}
}
}
} catch (SOAPFaultException sfe) {
println "fault string :" + sfe.message // faultcode/faultstring for 1.1 or Code/Reason for 1.2
println "envelope :" + sfe.text // prints SOAP Envelope
println "status code :" + sfe.httpResponse.statusCode
println sfe.fault.detail.text()
}
I'm pretty sure that the first send to the login is working since it's the code that works all on it's own and the error message I am receiving is
Unexpected subelement {urn:ws.company.com}emailAddress
So I'm guessing I'm okay up to that point, but can't figure it out. Based on the XML that works can anyone help me get my groovy code to work?
EDIT
Here's the response envelope from the login call
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<loginResponse xmlns="urn:ws.company.com">
<result>
<sessionId>string here</sessionId>
</result>
</loginResponse>
</soapenv:Body>
</soapenv:Envelope>
The problem may be with theSession = response.envelope which will set theSession to the entire SOAP response from the first call to login. My guess is that you really need to grab a token value from an element within the login response message, for example:
theSession = response.loginResponse.result.sessionId.text()
If you can provide a sample of the result from the call to login I can try to provide a more exact answer.

savon soap attributes

Am trying to query netsuite api for currencies. The following soap request works for me in SOAP UI client. But i am having a hard time trying to get the same working with ruby's savon gem version 0.9.7.
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:messages_2012_2.platform.webservices.netsuite.com" xmlns:urn1="urn:core_2012_2.platform.webservices.netsuite.com">
<soapenv:Header>
<urn:passport>
<urn1:email>xxx#abc.com</urn1:email>
<urn1:password>xxx</urn1:password>
<urn1:account>xxx</urn1:account>
</urn:passport>
</soapenv:Header>
<soapenv:Body>
<urn:getAll>
<urn:record recordType="currency"/>
</urn:getAll>
</soapenv:Body>
</soapenv:Envelope>
Basically i am not able to set the attribute on the urn:record element. The following is not working:
response = client.request :urn, :get_all do
soap.body = { "urn:record" => { :attributes! => { "recordType" => "currency" } } }
end
Please advise.
As explained on http://savonrb.com the key in the attributes! hash has to match the XML tag. You want to write something like this:
response = client.request :urn, :get_all do
soap.body = {'urn:record'=>'',
:attributes!=>{'urn:record'=>{'recordType'=>'currency'}}
}
end
Please let us know whether this solves it for you.
Double-check the raw soap request. :get_all may need to be "getAll" to have savon take you literally; it may be changing it to GetAll
In new versioin of savon you can place :attributes in the local context for the operation tag:
#interaction_client.call(:retrieve_interaction, message: message_hash, :attributes => { 'attachmentInfo' => include_attachments.to_s })
In this case, the attachmentInfo attribute will be placed into the main operation tag linked with operation, in this example this would be the ns:RetrieveInteractionRequest tag.
Please note that the syntax does not contains the exclamation mark.