Getting 400 bad request with WCF service called through WebRequest using C# - wcf

After some changes in code and going through loads of links I was able to write the following code to call WCF service method with SOAP message. Now I get 400 Bad Request error, whatever I change (tried HttpWebRequest) I still get this error. Not sure what am I missing:
private string WebServiceCall()
{
WebRequest req = WebRequest.Create("http://klo239fu.mass.win.tf.com/WCFTestService/Service.svc");
req.ContentType = "application/soap+xml; charset=utf-8";
req.Method = "POST";
req.Headers.Add("SOAPAction", "http://tempuri.org/GetSimpleType");
using(Stream reqStream = req.GetRequestStream())
{
var bytes = Encoding.UTF8.GetBytes(txtFormattedSoap.Text);
reqStream.Write(bytes, 0, bytes.Length);
reqStream.Close();
}
var wr = (WebRespose)req.GetResponse();
var srd = new StreamReader(wr.GetResponseStream());
txtResponse.Text = srd.ReadToEnd();
}
SOAP Request (from SOAP client)
POST /WCFTestService/Service.svc HTTP/1.1
Host: klo239fu.mass.win.tf.com
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "wsf-test-service/IService/GetSimpleType"
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetSimpleType xmlns="wsf-test-service">
<myvalue>int</myvalue>
</GetSimpleType>
</soap:Body>
</soap:Envelope>
Here is the SOAP request that is patterened to above soap enveope that I pass in my code:
<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><GetSimpleType xmlns="wcf-test-service"><myvalue>1234</myvalue></GetSimpleType></soap:Body></soap:Envelope>
Earlier I had content type test/xml but code throwed "(415) Cannot process the message because the content type 'text/xml' was not the expected type.". So I changed the content type="application/soap+xml; charset=utf-8" but it fails with (400) Bad request.

I'm saw antoher post you did and I think that you and I are currently working on the same thing. Invoking web services dynamically. Loading WSDLs, using dynamic proxies and reflection and all that fun stuff.
I have a suggestion for this error that you see.
I have had a similar issue with one of the web services I used. Even if the Action in the header is supposted to be optional, it did manage to get my call to fail when I passed in the address (uri) as you have. When I passed in the name of the operation instead it worked. So try and change this:
req.Headers.Add("SOAPAction", "http://tempuri.org/GetSimpleType");
To the name of the method in the WSDL instead. That is the name of the System.ServiceModel.Description.OperationDescription. It is probably "GetSimpleType".
req.Headers.Add("SOAPAction", "GetSimpleType");

Related

How to send a XML API request in cypress (SOAP API)

I need to send XML requests in cypress but I don't know how to do that. Generally, I worked with cy.request with rest API's. Is it possible to send XML requests in cypress?
How can I do that? Any help would be great!! An example would be lovely!
I left an example request that I use in postman without a problem. But to automate my test I need to send that request in cypress.
(POST request)
<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<MT_ServiceOrderInitiaionandMgmt xmlns:prx="***"
xmlns="***">
<VKONTO>***</VKONTO>
<NAME>***</NAME>
<PORTION>***</PORTION>
<AKLASSE/>
<DATUM>***</DATUM>
<Contact>
<RELTYP/>
<NAME>***</NAME>
<TEL_NUMBER>***</TEL_NUMBER>
<PHTYPE>***</PHTYPE>
<SMTP_ADDR>***</SMTP_ADDR>
</Contact>
<LifeSupportIndicator/>
<QMNUM>***</QMNUM>
<QMART>***</QMART>
<MNCOD>***</MNCOD>
<QMTXT>***</QMTXT>
<NOTST>***</NOTST>
<ServiceAddress>
<STREET>***</STREET>
<CITY1>***</CITY1>
<REGIO>***</REGIO>
<LOCATION>***</LOCATION>
<POST_CODE1>***</POST_CODE1>
<HAUS_NUM2/>
</ServiceAddress>
<ABLEINH>***</ABLEINH>
<CO_ASTTX>***</CO_ASTTX>
<STRMN/>
<STRUR>***</STRUR>
<LTRMN/>
<LTRUR>***</LTRUR>
<ERDAT>***</ERDAT>
<MZEIT>***</MZEIT>
<ERNAM>***</ERNAM>
<AEDAT/>
<AEZEIT>***</AEZEIT>
<AENAM/>
<PPSID>***</PPSID>
<ExternalReference>
<ID></ID>
<SYSNAME>***</SYSNAME>
<TYPE>***</TYPE>
</ExternalReference>
<REFNUM/>
<PRIOK/>
<LONT_TXT>***</LONT_TXT>
<PREMS>***</PREMS>
<Meters>
<TPLNR>***</TPLNR>
<VBSARTTEXT>***</VBSARTTEXT>
<TERMSCHL/>
<DLNOT>***</DLNOT>
<STORT>***</STORT>
<KTEXT>***</KTEXT>
<EINBDAT>***</EINBDAT>
<ISPRIM>***</ISPRIM>
<SERNR>***</SERNR>
<MET_SERNR></MET_SERNR>
<HERST>***</HERST>
<TYPBZ/>
<PREISKLA>***</PREISKLA>
<EQKTX>***</EQKTX>
<DSTAT>***</DSTAT>
<MEINS>***</MEINS>
<STANZVORE>***</STANZVORE>
<ISTABLART>***</ISTABLART>
<V_ZWSTAND></V_ZWSTAND>
<E_ZWSTANDO>***</E_ZWSTANDO>
<E_ZWSTANDU>***</E_ZWSTANDU>
<E_VERBERW>***</E_VERBERW>
<ADAT>***</ADAT>
<ATIM>***</ATIM>
<MTU_TPLNR/>
<MTUSN>***</MTUSN> >
<MTU_EQKTX/>
<MTU_EINBDAT>***11</MTU_EINBDAT>
<MTU_SERNR></MTU_SERNR>
<PORT>***</PORT>
</Meters>
</MT_ServiceOrderInitiaionandMgmt>
</soap:Body>
</soap:Envelope>
there are no big differences between standard rest API requests and XML Soap API requests.
cy.request({
method: "POST",
url: "Request URL",
headers: {
"Content-Type": "text/xml;charset=UTF-8",
authorization: "Bearer " + "auth token",
SOAPAction: "serviceOrder",
},
//you have to write your XML body here as a string. I leave a small part
//of my API's body to be an example if someone needs it in the future.
body: '<?xml version="1.0" encoding="UTF-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><MT_ServiceOrderInitiaionandMgmt xmlns:prx="***" xmlns="***"><VKONTO>5883000</VKONTO><NAME>cypress</NAME><PORTION>MBC87<MTU_EINBDAT>2002-05-11</MTU_EINBDAT><MTU_SERNR></MTU_SERNR><PORT>1</PORT></Meters></MT_ServiceOrderInitiaionandMgmt></soap:Body></soap:Envelope>',
})
.then((res) => {
//Do something with the response.
});

Slideshare api getting 'Failed API Validation' error response

I have applied for slideshare API and i got the API and the secret. All i have did is a simple GET request to slideshare which gives me results with the help of a tag.
This is my deluge script which i have tried to call the url using the API.
As per the documentation, i have got the unix time stamp and SHA1 hash.
param = Map();
param.put("api_key","XYZ");
param.put("ts","1565085930");
param.put("hash","xxxxxxxxxxxxxxxxxxxxxxxxx");
param.put("tag","cricket");
request = invokeurl
[
url :"https://www.slideshare.net/api/2/get_slideshows_by_tag"
type : GET
parameters: param
];
info request;
This is the response error i get:
<?xml version="1.0" encoding="UTF-8"?>
<SlideShareServiceError>
<Message ID="1">Failed API validation</Message>
</SlideShareServiceError>
Thank you.
Looks like the API does not work with a GET request. Try the same using a POST request and it should work. The same failed with POSTMAN and it worked only after the request type was changed to POST.
param = Map();
head = Map();
param.put("api_key","XXXXXXXX");
param.put("ts",1577955246);
param.put("hash","b3f3f803XXXXXXXXXXXXXXXX8be21d");
param.put("tag","cricket");
request = invokeurl
[
url :"https://www.slideshare.net/api/2/get_slideshows_by_tag"
type : POST
parameters: param
];
info request;
Response:
<?xml version="1.0" encoding="UTF-8"?>
<Tag>
<Name>cricket</Name>
<Count>0</Count>
</Tag>

eBay API: findItemsAdvanced returning "internal server error" with errorcode "500"

I'm trying to send a findItemsAdvanced request to the eBay API from VB 2012 .NET - however each time I get an "internal server error" with errorcode "500" upon request.GetResponse() where request = System.Net.WebRequest.Create("http://svcs.ebay.com/services/search/FindingService/v1"). I do the request via POST and in XML format with the lines
Dim Xml_bytes() As Byte = System.Text.Encoding.UTF8.GetBytes(xmlstr)
request = System.Net.WebRequest.Create("http://svcs.ebay.com/services/search/FindingService/v1")
'... code setting HEADERS, see below
request.Method = "POST"
request.ContentLength = Xml_bytes.Length
request.ContentType = "text/xml"
Dim requestStream As System.IO.Stream = request.GetRequestStream()
requestStream.Write(Xml_bytes, 0, Xml_bytes.Length)
requestStream.Close()
The code setting the headers I left out, instead here the actual finished headers I supply:
X-EBAY-SOA-SERVICE-NAME: FindingService
X-EBAY-SOA-OPERATION-NAME: findItemsAdvanced
X-EBAY-SOA-SERVICE-VERSION: 1.0.0
X-EBAY-SOA-GLOBAL-ID: EBAY-DE
X-EBAY-SOA-SECURITY-APPNAME: ****
X-EBAY-SOA-REQUEST-DATA-FORMAT: XML
Content-Type: text/xml
And finally the actual XML code which is supplied (through xmlstr var above):
<?xml version='1.0' encoding='utf-8'?>
<findItemsAdancedRequest xmlns='http://www.ebay.com/marketplace/search/v1/services'>
<keywords>caddy</keywords>
<categoryId>77994</categoryId>
<Version>779</Version>
<paginationInput><entriesPerPage>10</entriesPerPage>
</paginationInput>
</findItemsAdvancedRequest>
My main problem is: it does work perfectly with findItemsByKeywords! With the exact same code, only changing the find method and leaving out the <categoryId>77994</categoryId>.
What I tried to do:
different sites (US, german,..)
different categories and keywords.
live AND sandbox APIs with the correct appIDs
including or excluding X-EBAY-SOA-RESPONSE-DATA-FORMAT and/or
X-EBAY-SOA-REQUEST-DATA-FORMAT from the header
It's always the same: it works fine with findItemsByKeyword but I get the "internal server error" with findItemsAdvanced
I have run out of ideas - any suggestions?
Thanks!

Changing absolute URI to relative in HTTP POST header

I have the following POST request:
POST http://blah/Request HTTP/1.1
Host: blah
Content-Length: 322
Proxy-Connection: Keep-Alive
<?xml version="1.0"?>
<Envelope>
<Header>
<UserID>uid</UserID>
<Password>pass</Password>
<SessionID />
<RequestType>GetDetails</RequestType>
<POSCompany>01</POSCompany>
<PackageType>DATA</PackageType>
<ActionType>READ</ActionType>
<SnoopUserID />
</Header>
<Body>
<MagicNumber>124</MagicNumber>
</Body>
</Envelope>
This is failing with the error - (405) Method not supported
An example XML which apparently works on the server is the same but the header has the line POST /Request HTTP/1.1 instead of POST http://blah/Request HTTP/1.1.
I don't know if this is the problem but I am trying to eliminate all possibilites. However, I cannot get the POST request URI to be relative and not absolute. Is there a wat to do this?
The following is the code used for sending the XML.
Public Sub SendXML(ByVal file As String)
Dim reader As New StreamReader(file)
Dim data As String = reader.ReadToEnd()
reader.Close()
Dim request As HttpWebRequest = WebRequest.Create("http://blah/Request")
request.Method = "POST"
System.Net.ServicePointManager.Expect100Continue = False
Dim bytes As Byte() = System.Text.Encoding.ASCII.GetBytes(data)
request.ContentLength = bytes.Length
Dim oStreamOut As Stream = request.GetRequestStream()
oStreamOut.Write(bytes, 0, bytes.Length)
oStreamOut.Close()
Dim response As HttpWebResponse = request.GetResponse()
End Sub
Asked here in response to a request at 405 - Method Not Allowed HttpWebRequest
Following HTTP Error 405 Method not allowed
405 errors often arise with the POST method. You may be trying to
introduce some kind of input form on the Web site, but not all ISPs
allow the POST method necessary to process the form.
All 405 errors can be traced to configuration of the Web server and
security governing access to the content of the Web site, so should
easily be explained by your ISP.

405 - Method Not Allowed HttpWebRequest

I have a problem when trying to send a POST request. The sending method looks like this:
Public Sub SendXML(ByVal file As String)
Dim reader As New StreamReader(file)
Dim data As String = reader.ReadToEnd()
reader.Close()
Dim request As HttpWebRequest = WebRequest.Create("http://blah/Request")
request.Method = "POST"
System.Net.ServicePointManager.Expect100Continue = False
Dim bytes As Byte() = System.Text.Encoding.ASCII.GetBytes(data)
request.ContentLength = bytes.Length
Dim oStreamOut As Stream = request.GetRequestStream()
oStreamOut.Write(bytes, 0, bytes.Length)
oStreamOut.Close()
Dim response As HttpWebResponse = request.GetResponse()
End Sub
When running this I get the above error. Through Fiddler I can see that the request looks like:
POST http://blah/Request HTTP/1.1
Host: blah
Content-Length: 322
Proxy-Connection: Keep-Alive
<?xml version="1.0"?>
<Envelope>
<Header>
<UserID>uid</UserID>
<Password>pass</Password>
<SessionID />
<RequestType>GetDetails</RequestType>
<POSCompany>01</POSCompany>
<PackageType>DATA</PackageType>
<ActionType>READ</ActionType>
<SnoopUserID />
</Header>
<Body>
<MagicNumber>124</MagicNumber>
</Body>
</Envelope>
Now looking at this I suspected that it was due to the fact that the server does not accept POST messages. But some other reading suggests that the the URI http://blah/Request has been generated with a proxy and should be /Request so the line should read POST /Request HTTP/1.1
So what would be the common reason for this? And if it is a proxy problem, how is it sorted?
As asked below, I have created a new question for the more specific request. Changing absolute URI to relative in HTTP POST header
There is nothing wrong with the POST request, so the problem must lie elsewhere.
There are a number of other places along the way that could be causing trouble:
There could be a bad proxy between you and the server that is changing the HTTP method
The server could be malfunctioning or simply no support POST
My guess, however, is that the server is doing more than just looking at the HTTP method and is instead giving you a 405 error in response to the RPC call that your XML payload is wrapping.
Some RPC servers will (erroneously) use HTTP status codes like this to indicate that the requested method cannot be executed, or that something else is wrong with the request that is of a permissions and security nature.
If the server is slightly better behaved (and you are lucky), it should be returning additional information in the response body that might indicate where the 405 error is coming from.
Are you missing the Content-Type header required for a POST ?
Read here for details.
I assume it is mandatory.
Your POST appears to be completely invalid. POST data is supposed to be encoded (ie, as multipart/form-data) and use correct content-type (ie, application/x-www-form-urlencoded) with proper encoding and boundaries etc. You are just sending the server a lump of text and I'm not surprised it flips out.
I'm not 100% sure what VB is doing behind the scenes but this MSDN page suggests you need to set the content-type to a supported method and you probably need Content-Disposition: form-data in your headers as well. I found an example that does this and adds the MIME boundaries:
string FileData = "this is test file data\r\n"; // test data to send.
StringBuilder DataString = new StringBuilder();
DataString.Append(dataBoundary + "\r\n");
//This sends the viewstate info
DataString.Append("Content-Disposition: form-data; name=" + HiddenValue
+ "\r\n"
+ dataBoundary + "\r\n");
DataString.Append("Content-Disposition: form-data; name=" + "\"" +
"File1" +
"\"" +
"; filename=" + "\"" + "TestFile3.txt" + "\"" + "\r\n");
DataString.Append("Content-Type: text/plain\r\n\r\n");
DataString.Append(FileData);
DataString.Append(dataBoundary + "\r\n");
DataString.Append("Content-Disposition: form-data; name=" + "\"" +
"Submit1" +
"\"" + "\r\n\r\n" + "Upload\r\n" + dataBoundary + "--\r\n");
That example emulates a file field upload.
For a simpler version you can use request.ContentType = "application/x-www-form-urlencoded" with URL-encoded data like: Dim postData As String = "myURL=http%3A%2F%2Fexample.com%2Findex.php". Note that the format is key=value and the data must be URL-encoded first.
I'm not sure what exactly you need though because a lot depends on what the remote server actually expects for the form and field names. It also depends wether the server is actually following the relevant HTML standards and RFCs. Do you have a working HTML form to use as a guide for what the server expects?