C# 不用添加WebService引用,调用WebService方法
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。 [System.Web.Script.Services.ScriptService]
使用HttpWebRequest 向WebService发送POST请求,并将请求头:ContentType = "application/json;charset=utf-8",参数以JSON方式发送给WebService
/// <summary> /// 需要WebService支持Post调用 /// </summary> public static string PostWebServiceByJson(String URL, String MethodName, Hashtable Pars) { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL + "/" + MethodName); request.Method = "POST"; request.ContentType = "application/json;charset=utf-8"; request.Credentials = CredentialCache.DefaultCredentials; request.Timeout = 10000; byte[] data = Encoding.UTF8.GetBytes(HashtableToJson(Pars)); request.ContentLength = data.Length; Stream writer = request.GetRequestStream(); writer.Write(data, 0, data.Length); writer.Close(); StreamReader sr = new StreamReader(request.GetResponse().GetResponseStream(), Encoding.UTF8); String retXml = sr.ReadToEnd(); sr.Close(); return retXml; }
Hashtable ht = new Hashtable(); ht.Add("LoginName", "Admin"); ht.Add("Password", "Password"); ht.Add("AppKey", "123"); HttpHelper.PostWebServiceByJson("http://localhost/OpenApi/MobileService.asmx", "Login", ht);
WebService支持Post和Get方法
在Web.config添加下边节点
<webServices> <protocols> <add name="HttpGet"/> <add name="HttpPost"/> </protocols> </webServices>