客户端如何调用WebService并且POST数据
直接上代码
using System; using System.Collections.Generic; using System.Linq; using System.Text;using System.Net; using System.IO; namespace ETCRM.WebService.Tester { class Program { static void Main(string[] args) { try { //String Url = "http://localhost:3520/SynchDataInterface.asmx?op=SetSynchData"; //WeService Address,需要注意的是SetSynchData是WebService中公开的方法, //不要用?op=SetSynchData,无法调用,提示500 内部错误 String Url = "http://localhost:3520/SynchDataInterface.asmx/SetSynchData";
byte[] dataArray = Encoding.Default.GetBytes("需要Post到Server-side的data"); WebRequest req = WebRequest.Create(Url); req.Method = "POST"; req.ContentLength = dataArray.Length; req.ContentType = "application/x-www-form-urlencoded"; //创建输入流 Stream dataStream = req.GetRequestStream(); //发送请求 dataStream.Write(dataArray, 0, dataArray.Length); dataStream.Close(); //WebResponse res = req.GetResponse();// GetResponse blocks until the response arrives HttpWebResponse res = (HttpWebResponse)req.GetResponse(); Stream receiveStream = res.GetResponseStream(); //Read the stream into a string StreamReader sr = new StreamReader(receiveStream); string resultstring = sr.ReadToEnd(); Console.WriteLine(resultstring); Console.Read(); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.Read(); } } } }
只是一个Example,记录下来方便以后查阅,其他还需要注意的就是流的Close问题
需要注意编码问题,最好统一改成UIT-8
byte[] dataArray = Encoding.UTF8.GetBytes(XmlObjectHelper.ObjectToXML(postData));