Client to send SOAP request to web service - c#

I am trying to send SOAP request to my web service and from this question - Client to send SOAP request and received response
I got this piece of code:
using System.Xml;
using System.Net;
using System.IO;
public static void CallWebService()
{
var _url = "http://xxxxxxxxx/Service1.asmx";
var _action = "http://xxxxxxxx/Service1.asmx?op=HelloWorld";
XmlDocument soapEnvelopeXml = CreateSoapEnvelope();
HttpWebRequest webRequest = CreateWebRequest(_url, _action);
InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);
// begin async call to web request.
IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);
// suspend this thread until call is complete. You might want to
// do something usefull here like update your UI.
asyncResult.AsyncWaitHandle.WaitOne();
// get the response from the completed web request.
string soapResult;
using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))
{
using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
{
soapResult = rd.ReadToEnd();
}
Console.Write(soapResult);
}
}
private static HttpWebRequest CreateWebRequest(string url, string action)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Headers.Add("SOAPAction", action);
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
return webRequest;
}
private static XmlDocument CreateSoapEnvelope()
{
XmlDocument soapEnvelopeDocument = new XmlDocument();
soapEnvelopeDocument.LoadXml(#"<SOAP-ENV:Envelope xmlns:SOAP-ENV=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsi=""http://www.w3.org/1999/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/1999/XMLSchema""><SOAP-ENV:Body><HelloWorld xmlns=""http://tempuri.org/"" SOAP-ENV:encodingStyle=""http://schemas.xmlsoap.org/soap/encoding/""><int1 xsi:type=""xsd:integer"">12</int1><int2 xsi:type=""xsd:integer"">32</int2></HelloWorld></SOAP-ENV:Body></SOAP-ENV:Envelope>");
return soapEnvelopeDocument;
}
private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
{
using (Stream stream = webRequest.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
}
But it doesn't work for me, it says there is no definition for GetRequestStream() and Headers where you add the SOAPAction under HttpWebRequest, can anyone help me solve the problem?
Edit:
The Errors occur on the line
using (Stream stream = webRequest.GetRequestStream())
And it gives the error
Error CS1061 'HttpWebRequest' does not contain a definition for 'GetRequestStream' and no extension method 'GetRequestStream' accepting a first argument of type 'HttpWebRequest' could be found (are you missing a using directive or an assembly reference?)
And another error on the line
webRequest.Headers.Add("SOAPAction", action);
And it gives the error
Error CS1929 'WebHeaderCollection' does not contain a definition for 'Add' and the best extension method overload 'SettersExtensions.Add(IList, BindableProperty, object)' requires a receiver of type 'IList'

Use for adding headers:
webRequest.Headers["HeaderToken"] = "HeaderValue";
And for GetRequestStream use:
using (var stream = await Task.Factory.FromAsync<Stream>(webRequest.BeginGetRequestStream, webRequest.EndGetRequestStream, null))
{
reqBody.Save(stream);
}

Related

Send XML document over soap

Following is my code:
Method(SendXmlDocument) will take in as parameter an XML document, URL, and the SOAP action and make a request to a web service. I have to use HttpClient class to make the request to the web service.
using System;
using System.Net;
using System.Threading.Tasks;
using System.Xml;
using System.IO;
namespace HttpClientStatus
{
class WebServiceClient
{
public void SendXmlDocument(XmlDocument fi , string URL , string action)
{
XmlDocument soapEnvelopeXml = fi;
HttpWebRequest webRequest = CreateWebRequest(URL, action);
InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);
IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);
asyncResult.AsyncWaitHandle.WaitOne();
// get the response from the completed web request.
string soapResult;
using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))
{
using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
{
soapResult = rd.ReadToEnd();
}
Console.Write(soapResult);
}
}
private static HttpWebRequest CreateWebRequest(string url, string action)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Headers.Add("SOAPAction", action);
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
return webRequest;
}
private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
{
using (Stream stream = webRequest.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
}
}
class Program
{
static void Main(string[] args)
{
var _u = "http://xxxxxxxxx/Service1.asmx";
var _a = "http://xxxxxxxxx/Service1.asmx/action";
XmlDocument d = new XmlDocument();
d.Load("C://Users//gmzmdz//Desktop//course.xml");
WebServiceClient ob = new WebServiceClient();
ob.SendXmlDocument(d, _u, _a);
}
}
}
My Question is that following pure xml document will be sent or not. That this method make a request to web service or not. How do I will know about it that request has been made successful? Then, I have to print the response on the console that comes back from the web service.

Consume Amadeus Soap4.0 in C#

C# Code:
public static void CallWebService(string XmlText)
{
try
{
var _url = "https://nodeD1.test.webservices.amadeus.com/1ASIWMLFPNP";// "https://noded1.test.webservices.amadeus.com/1asiwmlfpnp";
var _action = "http://webservices.amadeus.com/fmptbq_14_3_1a";
XmlDocument soapEnvelopeXml = CreateSoapEnvelope(XmlText);
HttpWebRequest webRequest = CreateWebRequest(_url, _action);
webRequest = InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);
// begin async call to web request.
IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);
// suspend this thread until call is complete. You might want to
// do something usefull here like update your UI.
asyncResult.AsyncWaitHandle.WaitOne();
// get the response from the completed web request.
string soapResult;
using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))
{
using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
{
soapResult = rd.ReadToEnd();
}
Console.Write(soapResult);
}
}
catch (WebException webex)
{
WebResponse errResp = webex.Response;
using (Stream respStream = errResp.GetResponseStream())
{
StreamReader reader = new StreamReader(respStream);
string text = reader.ReadToEnd();
}
}
}
private static HttpWebRequest CreateWebRequest(string url, string action)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Headers.Add("SOAPAction", action);
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
return webRequest;
}
private static XmlDocument CreateSoapEnvelope(string XmlText)
{
XmlDocument soapEnvelopeDocument = new XmlDocument();
soapEnvelopeDocument.LoadXml(string.Format(#"{0}",XmlText));
return soapEnvelopeDocument;
}
private static HttpWebRequest InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
{
using (Stream stream = webRequest.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
return webRequest;
}
}
Request:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sec="http://xml.amadeus.com/2010/06/Security_v1" xmlns:typ="http://xml.amadeus.com/2010/06/Types_v1" xmlns:iat="http://www.iata.org/IATA/2007/00/IATA2010.1" xmlns:app="http://xml.amadeus.com/2010/06/AppMdw_CommonTypes_v3" xmlns:link="http://wsdl.amadeus.com/2010/06/ws/Link_v1" xmlns:ses="http://xml.amadeus.com/2010/06/Session_v3" xmlns:fmp="http://xml.amadeus.com/FMPTBQ_14_3_1A">
<soapenv:Header>
<add:MessageID xmlns:add="http://www.w3.org/2005/08/addressing">29e8e874-3033-dd52-6b75-a2da58e10291</add:MessageID>
<add:Action xmlns:add="http://www.w3.org/2005/08/addressing">http://webservices.amadeus.com/fmptbq_14_3_1A</add:Action>
<add:To xmlns:add="http://www.w3.org/2005/08/addressing">https://noded1.test.webservices.amadeus.com/1asiwmlfpnp</add:To>
<link:TransactionFlowLink xmlns:link="http://wsdl.amadeus.com/2010/06/ws/Link_v1"/>
<oas:Security xmlns:oas="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<oas:UsernameToken oas1:Id="UsernameToken-1" xmlns:oas1="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<oas:Username>WSPNPMLF</oas:Username>
<oas:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">bTEzbk5LNElzZw==</oas:Nonce>
<oas:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">5lkky7mUVRujQPg4blzfKi5dSyg=</oas:Password>
<oas1:Created>2017-12-15T13:43:34:532Z</oas1:Created>
</oas:UsernameToken>
</oas:Security>
<AMA_SecurityHostedUser xmlns="http://xml.amadeus.com/2010/06/Security_v1">
<UserID AgentDutyCode="SU" POS_Type="1" PseudoCityCode="BLRVS32CY" RequestorType="U"/>
</AMA_SecurityHostedUser>
</soapenv:Header>
<soapenv:Body>
<Fare_MasterPricerTravelBoardSearch>
<numberOfUnit>
<unitNumberDetail>
<numberOfUnits>1</numberOfUnits>
<typeOfUnit>PX</typeOfUnit>
</unitNumberDetail>
<unitNumberDetail>
<numberOfUnits>250</numberOfUnits>
<typeOfUnit>RC</typeOfUnit>
</unitNumberDetail>
</numberOfUnit>
<paxReference>
<ptc>ADT</ptc>
<traveller>
<ref>1</ref>
</traveller>
</paxReference>
<fareOptions>
<pricingTickInfo>
<pricingTicketing>
<priceType>RP</priceType>
<priceType>RU</priceType>
<priceType>TAC</priceType>
<priceType>ET</priceType>
</pricingTicketing>
</pricingTickInfo>
</fareOptions>
<travelFlightInfo>
<cabinId>
<cabinQualifier>RC</cabinQualifier>
<cabin>Y</cabin>
</cabinId>
</travelFlightInfo>
<itinerary>
<requestedSegmentRef>
<segRef>1</segRef>
</requestedSegmentRef>
<departureLocalization>
<depMultiCity>
<locationId>DEL</locationId>
</depMultiCity>
</departureLocalization>
<arrivalLocalization>
<arrivalMultiCity>
<locationId>BOM</locationId>
</arrivalMultiCity>
</arrivalLocalization>
<timeDetails>
<firstDateTimeDetail>
<timeQualifier>TD</timeQualifier>
<date>201217</date>
<time>0000</time>
<timeWindow></timeWindow>
</firstDateTimeDetail>
</timeDetails>
</itinerary>
<itinerary>
<requestedSegmentRef>
<segRef>1</segRef>
</requestedSegmentRef>
<departureLocalization>
<depMultiCity>
<locationId>BOM</locationId>
</depMultiCity>
</departureLocalization>
<arrivalLocalization>
<arrivalMultiCity>
<locationId>DEL</locationId>
</arrivalMultiCity>
</arrivalLocalization>
<timeDetails>
<firstDateTimeDetail>
<timeQualifier>TD</timeQualifier>
<date>251217</date>
<time>0000</time>
<timeWindow></timeWindow>
</firstDateTimeDetail>
</timeDetails>
</itinerary>
</Fare_MasterPricerTravelBoardSearch>
</soapenv:Body>
</soapenv:Envelope>
Response:
<?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>12|Presentation|soap message header incorrect</faultstring>
<faultactor>SI:muxDZ2</faultactor>
</soap:Fault>
</soap:Body>
</soap:Envelope>
When the same request is passed using SoapUI im getting response but when C# Code is used im getting the above response.. if any one have implemented Amadeus Soap4.0 API in C# please help.
Maybe you have setup SoapUI to perform additional actions on the request payload (thus the request is not the same) ?
I would advise to create a proxy class from the given WSDL. While this proxy class doesn't support Nonce by default, it's extensible. check out WCF: Adding Nonce to UsernameToken
Now the 12 error code you get could also derive from other things.... Like for example I don't see your <Session /> element there (unless this represents a stateless request?)

Too many automatic redirects have been attempted in WebClient

I need to allow redirection in my WebClient 'cause I've this url:
http://int.soccerway.com/national/algeria/ligue-2/c207/
when I add this in the browser I'll get a redirect to this:
http://int.soccerway.com/national/algeria/ligue-2/20172018/regular-season/r43168/
when I perform a request I execute this method:
public static string GetData(string url)
{
HttpWebRequest webReq = (HttpWebRequest)HttpWebRequest.Create(url);
try
{
webReq.CookieContainer = new CookieContainer();
webReq.Method = "GET";
webReq.AllowAutoRedirect = true;
webReq.MaximumAutomaticRedirections = 1;
using (WebResponse response = webReq.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream);
return reader.ReadToEnd();
}
}
...
}
but this throws an exception:
Too many automatic redirects have been attempted
other threads suggest to add a cookie container, I did so but the error happen occurs again. How can I solve this?

Getting the response of Asynchronous http web request using POST method in asp.net core

I am using asp.net core. I am able to get the response from the http webrequest using GET method. To get the response via http webrequest using POST am facing 405 error.(Remote server not found)
Here is my code using GET Method.
public static void Main(string[] args)
{
var task = MakeAsyncRequest("http://localhost:8080/nifi-api/flow/status", "text/html");
Console.ReadLine();
}
public static Task<string> MakeAsyncRequest(string url, string contentType)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = contentType;
request.Method = "GET";
request.Proxy = null;
Task<WebResponse> task = Task.Factory.FromAsync(
request.BeginGetResponse,
asyncResult => request.EndGetResponse(asyncResult),
(object)null);
return task.ContinueWith(t => ReadStreamFromResponse(t.Result));
}
private static string ReadStreamFromResponse(WebResponse response)
{
using (Stream responseStream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(responseStream))
{
string results = reader.ReadToEnd();
if (!string.IsNullOrEmpty(results))
{
Data data = new Data();
data = JsonConvert.DeserializeObject<Data>(results);
}
return results;
}
}
Please let me know how to get the response using async POST method in asp.net core. Thanks in advance.
Maybe this way?
HttpClient httpClient = new HttpClient();
var response = await httpClient.PostAsync("http://localhost:8080/nifi-api/flow/status", new StringContent("Json string", Encoding.UTF8, "application/json"));

How to post data on JSON web services in Windows Phone 8

I want to post data on JSON web services for login credentials for user.
I use the below code to post data on JSON web service.
private void Button_Click_1(object sender, RoutedEventArgs e)
{
// Create a new HttpWebRequest object.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://test/TestService/Service.svc/json/Login");
request.ContentType = "application/json";
//request.UserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0; Touch)";
// request.CookieContainer = cookie;
// Set the Method property to 'POST' to post data to the URI.
request.Method = "POST";
// start the asynchronous operation
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
}
private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
Stream postStream = request.EndGetRequestStream(asynchronousResult);
//postData value
string postData = "{'userid': '" + textUserid.Text + "','password':'" + textPassword.Text + "'}";
// Convert the string into a byte array.
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Write to the request stream.
postStream.Write(byteArray, 0, postData.Length);
postStream.Close();
// Start the asynchronous operation to get the response
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
private void GetResponseCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string read = streamRead.ReadToEnd();
//respond from httpRequest
//TextBox.Text = read;
MessageBox.Show("Your Response: " + read);
// Close the stream object
streamResponse.Close();
streamRead.Close();
response.Close();
}
and I import following namespace in my code
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Text;
I am calling Button_Click_1 method clicking login button from my Windows Phone simulator.
But I am getting this error:
Error 1 'System.Net.WebRequest' does not contain a definition for 'GetRequestStream' and no extension method 'GetRequestStream' accepting a first argument of type 'System.Net.WebRequest' could be found (are you missing a using directive or an assembly reference?) E:\Users\maan\Documents\Visual Studio 2012\Projects\TestWebservice\TestWebservice\MainPage.xaml.cs 99 39 TestWebservice
and
Error 2 'System.Net.WebRequest' does not contain a definition for 'GetResponse' and no extension method 'GetResponse' accepting a first argument of type 'System.Net.WebRequest' could be found (are you missing a using directive or an assembly reference?) E:\Users\maan\Documents\Visual Studio 2012\Projects\TestWebservice\TestWebservice\MainPage.xaml.cs 106 39 TestWebservice
Please help me I am new to developing Windows mobile application.
Please check the below code, i hope it will help you:
void sendRequest()
{
Uri myUri = new Uri(http://www.yourwebsite.com);
HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(myUri);
myRequest.Method = AppResources.POST;
myRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), myRequest);
}
void GetRequestStreamCallback(IAsyncResult callbackResult)
{
HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
// End the stream request operation
Stream postStream = myRequest.EndGetRequestStream(callbackResult);
// Create the post data
string postData = "INSERT HERE THE JASON YOU WANT TO SEND";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Start the web request
myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallback), myRequest);
}
void GetResponsetStreamCallback(IAsyncResult callbackResult)
{
lib = new ApiLibrary();
try
{
HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
string result = "";
using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
{
result = httpWebStreamReader.ReadToEnd();
}
string APIResult = result;
}
catch (Exception e)
{
}
}

Categories