Calling Soap web service over HTTP giving exception "Connection close" - c#

I am calling third party Web service over HTTP but it is failing to connect in WPF application/Console Application. Exception is connection close. Wondering why it is closed though same SOAP message works in SOAP UI. Can I give Action with URN as I copyed from SOAP UI. Please suggest what is wrong. Since it is not using browser so cros domain problem should not be.
My C# code is as follows.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml;
namespace CTWpfApp
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
CallWebService();
}
public static void CallWebService()
{
var _url = "https://myService.com/webservices/ct/services/4.1";
var _action = "urn:provider/interface/ctservices/getCPNInstances";
XmlDocument soapEnvelopeXml = CreateSoapEnvelope();
HttpWebRequest webRequest = CreateWebRequest(_url, _action);
InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);
// Start the asynchronous operation to get the response
webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
}
private static void GetResponseCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation /* I'm getting the exception Connection Close."*/
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
Console.WriteLine(responseString);
// Close the stream object
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse
response.Close();
}
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";
webRequest.KeepAlive = false;
webRequest.Timeout = 300000;
return webRequest;
}
private static XmlDocument CreateSoapEnvelope()
{
XmlDocument soapEnvelop = new XmlDocument();
soapEnvelop.LoadXml(#"<SOAP-ENV:Envelope xmlns:SOAP-ENV=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:ns1=""urn:dictionary:com.ct.webservices""><SOAP-ENV:Header xmlns:wsse=""http://docs.myses.org/wss/2004/01/200401-wss-wssecurity-secext-1.0.xsd""><wsse:Security SOAP-ENV:mustUnderstand=""1""><wsse:UsernameToken><wsse:Username>fiwjiueji</wsse:Username><wsse:Password Type=""http://docs.myses.org/wss/2004/01/200401-wss-username-token-profile-1.0#PasswordText"">tjrrfrsi</wsse:Password></wsse:UsernameToken></wsse:Security></SOAP-ENV:Header><SOAP-ENV:Body><ns1:getCPNInstances></ns1:getCPNInstances></SOAP-ENV:Body></SOAP-ENV:Envelope>");
return soapEnvelop;
}
private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
{
using (Stream stream = webRequest.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
}
}
}

Take out the webRequest.KeepAlive = false in the CreateWebRequest method.
When using HTTP/1.1, Keep-Alive is on by default. Setting KeepAlive to false may result in sending a Connection: Close header to the server. -From http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.keepalive.aspx

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.

Unable to make http call from c# DLL

I have created a c# library in Visual Studio 2019 on my mac. I am trying to expose a method in my dll which should have the capacity to make an http call and return the response.
But I am getting the error Cannot send a content-body with this verb-type.
I am very new to c#, so I just copy-pasted code from online. Please show me what wrong I am doing.
My Library,
using System;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
namespace ImageTrainer
{
public class Trainer
{
public static void TrainImage()
{
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)WebRequest.Create("https://www.abcd.com/rest/city/search/Bang");
request.Method = "GET";
request.ContentType = "application/json";
// // request.ContentLength = DATA.Length;
StreamWriter requestWriter = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
// // requestWriter.Write(DATA);
requestWriter.Close();
WebResponse webResponse = request.GetResponse();
Stream webStream = webResponse.GetResponseStream();
StreamReader responseReader = new StreamReader(webStream);
string response = responseReader.ReadToEnd();
Console.WriteLine(response);
// responseReader.Close();
// Console.WriteLine(response);
}
}
}
and I am using the library in another console application.
using System;
using ImageTrainer;
namespace ImageTrainerTest
{
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
Trainer.TrainImage();
}
}
}
What mistake am I making?
Remove these 2 lines:
StreamWriter requestWriter = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
requestWriter.Close();
As you are making GET request, you should not have any body, otherwise you should use POST verb.

Client to send SOAP request to web service

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

The 'Content-Type' header must be modified using the appropriate property or method. Parameter name: name

Hi I am using HttpWebRequest GET method to call a REST service. I am getting error :- ***'Content-Type' header must be modified using the appropriate property or method. Parameter name: name.***i checked all answer related this issue from stackoverflow.
My Code:-
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
Getvalue(TextBox1.Text,TextBox2.Text,TextBox3.Text);
}
private void Getvalue(string text1, string text2, string text3)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.KeepAlive = true;
request.ContentType = "appication/json";
request.Headers.Add("Content-Type", "appication/json");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string myResponse = "";
using (System.IO.StreamReader sr = new system.IO.StreamReader(response.GetResponseStream()))
{
myResponse = sr.ReadToEnd();
}
Response.Write(myResponse);
}
}
I too ended up with this problem. But realized the issue is with how you setting the content type.
The proper way to set is
request.ContentType = "application/json";

Cannot set CookieContainer due to the state of the HttpWebRequest object error?

I am currently trying to login and get cookies to a remote server using windows phone 7 silverlight in visual studio. I managed to login and get a successful result for login, but when I try to put in the codes to get cookies, it just failed.
It produced error "Cannot set CookieContainer due to the state of the HttpWebRequest object." on my code "request.CookieContainer = new CookieContainer();"
Can anyone helps me? I can't seem to find the error and I try to look at the documentation and examples but with no luck. Below is my full codes on windows phone 7.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO;
using System.IO.IsolatedStorage;
namespace Testing_Login_
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
}
private void buttonLogin_Click(object sender, RoutedEventArgs e)
{
//HttpWebRequest req = WebRequest.Create();
string POST_ADDRESS = "http://mywebsite.com";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(POST_ADDRESS, UriKind.Absolute));
request.Method = "POST";
// don't miss out this
request.ContentType = "application/x-www-form-urlencoded";
request.BeginGetRequestStream(new AsyncCallback(RequestReady), request);
}
// Sumbit the Post Data
void RequestReady(IAsyncResult asyncResult)
{
HttpWebRequest request = asyncResult.AsyncState as HttpWebRequest;
Stream stream = request.EndGetRequestStream(asyncResult);
// Hack for solving multi-threading problem
// I think this is a bug
this.Dispatcher.BeginInvoke(delegate()
{
// Send the post variables
StreamWriter writer = new StreamWriter(stream);
writer.Write("username=" + textBoxUsername.Text + "&password=" + passwordBoxSTAMP.Password);
writer.Flush();
writer.Close();
request.CookieContainer = new CookieContainer();
request.BeginGetResponse(new AsyncCallback(ResponseReady), request);
});
}
// Get the Result
void ResponseReady(IAsyncResult asyncResult)
{
HttpWebRequest request = asyncResult.AsyncState as HttpWebRequest;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);
this.Dispatcher.BeginInvoke(delegate()
{
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
// get the result text
string result = reader.ReadToEnd();
if (result == "TRUE")
{
MessageBox.Show("Login Successful!");
//CookieCollection cookieValue = response.Cookies;
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isfs = isf.OpenFile("CookieExCookies", FileMode.OpenOrCreate, FileAccess.Write))
{
using (StreamWriter sw = new StreamWriter(isfs))
{
foreach (Cookie cookieValue in response.Cookies)
{
sw.WriteLine("Cookie: " + cookieValue.ToString());
}
sw.Close();
}
}
}
//MessageBox.Show(cookieValue.ToString());
}
else if (result == "ICRED")
{
MessageBox.Show("Username or Password incorrect!");
}
else
{
MessageBox.Show("Unknown Error!"+result);
}
});
}
private void ReadFromIsolatedStorage()
{
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isfs =
isf.OpenFile("CookieExCookies", FileMode.Open))
{
using (StreamReader sr = new StreamReader(isfs))
{
textBoxCookies.Text = sr.ReadToEnd();
sr.Close();
}
}
}
}
}
}
Move the line:-
request.CookieContainer = new CookieContainer();
out of RequestReady and put it in buttonLogin_Click just after you have constructed it.
OR since you aren't re-using it anywhere ditch line altogether.
OR if in fact for things to really work you need to re-use it then construct and hold it somewhere else (such as a field in the class) and assign it to each Request object created before you invoke any BeginGetRequestStream or BeginGetResponse.

Categories