在项目过程中,我们也许会遇到一种场景,需要跨域请求页面内容,而通常我们用JQuery写的ajax却又是不可跨域请求的,这时我们可以考虑使用.net提交请求,并获取响应内容。
代码:
string formUrl = AppSettingUtil.GetString("GB.SyncLoginPostUrl"); //请求的URL地址 string formData = "userId={0}&token={1}".FormatWith(userName, postToken);//POST的数据 //注意提交的编码 这边是需要改变的 这边默认的是Default:系统当前编码 var postData = Encoding.UTF8.GetBytes(formData); //设置提交的相关参数 HttpWebRequest request = WebRequest.Create(formUrl) as HttpWebRequest; request.Method = "POST"; request.KeepAlive = false; request.AllowAutoRedirect = true; request.ContentType = Request.ContentType; request.UserAgent = Request.UserAgent; request.ContentLength = postData.Length; //提交请求数据 var outputStream = request.GetRequestStream(); outputStream.Write(postData, 0, postData.Length); outputStream.Close(); var response = request.GetResponse() as HttpWebResponse; var responseStream = response.GetResponseStream(); var reader = new StreamReader(responseStream, Encoding.GetEncoding("UTF-8")); var srcString = reader.ReadToEnd(); string result = srcString; //返回值赋值 reader.Close();