Httwebrequest调用webservice
Posted &‘米粒
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Httwebrequest调用webservice相关的知识,希望对你有一定的参考价值。
webservice的webconfig配置,不配置后面会报远程服务器返回错误: (500) 内部服务器错误,跨域错误。
<system.web> <compilation debug="true" targetFramework="4.0" /> <webServices> <protocols> <add name= "HttpPost"/> <add name= "HttpGet"/> </protocols> </webServices> </system.web>
<configuration> <system.webServer> <httpProtocol> <customHeaders> <add name="Access-Control-Allow-Methods" value="OPTIONS,POST,GET"/> <add name="Access-Control-Allow-Headers" value="x-requested-with,content-type"/> <add name="Access-Control-Allow-Origin" value="*" /> </customHeaders> </httpProtocol> <modules> <add name="MyHttpModule" type="WebServiceDemo.MyHttpModule"/> </modules> </system.webServer> </configuration>
如果报错:
未能加载类型“WebServiceDemo.MyHttpModule”。去掉
<modules> <add name="MyHttpModule" type="WebServiceDemo.MyHttpModule"/> </modules>
webserviceDemo.asmx
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; namespace News.webservice { /// <summary> /// WebServiceDemo 的摘要说明 /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。 [System.Web.Script.Services.ScriptService] public class WebServiceDemo : System.Web.Services.WebService { [WebMethod] public string HelloWorld(string name,string name1) { return name+name1; } } }
前台调用
$.ajax({ type: "POST", //访问WebService使用Post方式请求 contentType: "application/json;charset=utf-8", //WebService 会返回Json类型 url: "http://localhost:1071/webservice/WebServiceDemo.asmx/HelloWorld", data: "{name:\\"" + 123 + "\\"}", //企业id参数 dataType: \'json\', beforeSend: function (x) { x.setRequestHeader("Content-Type", "application/json; charset=utf-8"); }, error: function (x, e) { alert(\'fail\'); }, success: function (result) { //回调函数,result,返回值 alert(JSON.stringify(result)); } });
后台调用 转自:http://www.cnblogs.com/ghelement/p/5286630.html
static void Main(string[] args) { string a= GetStringByUrl("http://localhost:1071/webservice/WebServiceDemo.asmx/HelloWorld?name=youchim"); string b= RequestWebService("http://localhost:1071/webservice/WebServiceDemo.asmx/HelloWorld","name=朱一届&name1=youchim"); } //get public static string GetStringByUrl(string strUrl) { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strUrl); req.UserAgent = "MSIE6.0"; req.Method = "GET"; //http://www.cnblogs.com/cresuccess/archive/2009/12/09/1619977.html HttpWebResponse res; try { res = (HttpWebResponse)req.GetResponse(); } catch (WebException ex) { res = (HttpWebResponse)ex.Response; } StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.GetEncoding("UTF-8")); string strHtml = sr.ReadToEnd(); sr.Close(); res.Close(); return strHtml; } //post方法 public static string RequestWebService(string strUrl, string strPostData) { try { //构造请求 HttpWebRequest hwrRequest = (HttpWebRequest)WebRequest.Create(strUrl); hwrRequest.Method = "POST"; hwrRequest.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-shockwave-flash, */*"; hwrRequest.Headers.Add("Accept-Encoding", "gzip, deflate"); hwrRequest.Headers.Add("Accept-Language", "zh-cn"); hwrRequest.Headers.Add("Cache-Control", "gzip, deflate"); hwrRequest.Headers.Add("KeepAlive", "TRUE"); hwrRequest.Headers.Add("ContentLength", strPostData.Length.ToString()); hwrRequest.ContentType = "application/x-www-form-urlencoded"; hwrRequest.Referer = strUrl; hwrRequest.Headers.Add("UA-CPU", "x86"); hwrRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; hwrRequest.Timeout = 30000; hwrRequest.ServicePoint.Expect100Continue = false; //发送请求 byte[] bytPostData = Encoding.UTF8.GetBytes(strPostData); Stream strStream = hwrRequest.GetRequestStream(); strStream.Write(bytPostData, 0, bytPostData.Length); strStream.Close(); //就收应答 HttpWebResponse hwrResponse = (HttpWebResponse)hwrRequest.GetResponse(); Stream strStream1 = null; if (hwrResponse.ContentEncoding == "gzip") { System.IO.Compression.GZipStream gzsStream = new System.IO.Compression.GZipStream(hwrResponse.GetResponseStream(), System.IO.Compression.CompressionMode.Decompress); strStream1 = gzsStream; } else { strStream1 = hwrResponse.GetResponseStream(); } string strResult = new StreamReader(strStream1, System.Text.Encoding.UTF8).ReadToEnd(); hwrResponse.Close(); return strResult; } catch (Exception excResult) { return ""; } }
以上是关于Httwebrequest调用webservice的主要内容,如果未能解决你的问题,请参考以下文章