您好,登錄后才能下訂單哦!
這篇文章主要介紹了C#中如何使用HttpPost調用WebService,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
WebService服務端代碼
public class WebServiceDemo : System.Web.Services.WebService { [WebMethod] public string HelloWorld() { return "Hello World"; } [WebMethod] public string Sum(string param1, string param2) { int num1 = Convert.ToInt32(param1); int num2 = Convert.ToInt32(param2); int sum = num1 + num2; return sum.ToString(); } }
客戶端調用代碼
class Program { static void Main(string[] args) { Program program = new Program(); string url = "http://localhost:12544/WebServiceDemo.asmx"; string method = "Sum"; string num1 = "1"; string num2 = "2"; string result = program.HttpPostWebService(url, method, num1, num2); Console.WriteLine(result); Console.ReadKey(); } public string HttpPostWebService(string url,string method,string num1,string num2) { string result = string.Empty; string param = string.Empty; byte[] bytes = null; Stream writer = null; HttpWebRequest request = null; HttpWebResponse response = null; param = HttpUtility.UrlEncode("param1") + "=" + HttpUtility.UrlEncode(num1) + "&" + HttpUtility.UrlEncode("param2") + "=" + HttpUtility.UrlEncode(num2); bytes = Encoding.UTF8.GetBytes(param); request = (HttpWebRequest)WebRequest.Create(url + "/" + method); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = bytes.Length; try { writer = request.GetRequestStream(); //獲取用于寫入請求數據的Stream對象 } catch (Exception ex) { return ""; } writer.Write(bytes, 0, bytes.Length); //把參數數據寫入請求數據流 writer.Close(); try { response = (HttpWebResponse)request.GetResponse(); //獲得響應 } catch (WebException ex) { return ""; } #region 這種方式讀取到的是一個返回的結果字符串 Stream stream = response.GetResponseStream(); //獲取響應流 XmlTextReader Reader = new XmlTextReader(stream); Reader.MoveToContent(); result = Reader.ReadInnerXml(); #endregion #region 這種方式讀取到的是一個Xml格式的字符串 //StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); //result = reader.ReadToEnd(); #endregion response.Dispose(); response.Close(); //reader.Close(); //reader.Dispose(); Reader.Dispose(); Reader.Close(); stream.Dispose(); stream.Close(); return result; } }
如果遇到調用時報錯,可以嘗試在WebService的web.config配置文件中添加如下節點
<system.web> <webServices> <protocols> <add name="HttpPost" /> </protocols> </webServices> </system.web>
感謝你能夠認真閱讀完這篇文章,希望小編分享的“C#中如何使用HttpPost調用WebService”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,更多相關知識等著你來學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。