Calling a web method using HttpWebRequest and HttpWebResponse.
Service1.asmx.cs
---------------------
using System;
using System.Data;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.ComponentModel;
namespace WebService1
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
public class Service1 : System.Web.Services.WebService
{
[WebMethod]
public int Add(int a, int b)
{
return a + b;
}
}
}
Class1.cs
---------
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Net;
using System.IO;
namespace WebService1
{
public class Class1
{
public string GetResponse(string InputXML, string WebserviceURL, string strSoapAction)
{
string postData = InputXML;
UTF8Encoding encoding = new UTF8Encoding();
byte[] postBytes = encoding.GetBytes(postData);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(WebserviceURL);
req.Method = "POST";
req.ContentType = "text/xml; charset=utf-8";
req.Headers.Add("SOAPAction", strSoapAction);
req.ContentLength = postBytes.Length;
Stream postStreem = req.GetRequestStream();
postStreem.Write(postBytes, 0, postBytes.Length);
postStreem.Close();
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
StreamReader reader = new StreamReader(res.GetResponseStream());
return reader.ReadToEnd();
}
}
}
Method call:
-------------
Class1 obj = new Class1();
string str = obj.GetResponse(TextBox1.Text, "http://localhost:62202/Service1.asmx", "http://tempuri.org/Add");
Response.Write("Response from Webservice:
Sum of two numbers: " + str);
1 comment:
Thanks for your code.. but i getting Error like this: the remote server returned an error (400) bad request.
Post a Comment