asp.net中WebResponse 跨域访问示例

前两天,一个朋友让我帮他写这样一个程序:在asp.net里面访问asp的页面,把数据提交对方的数据库后,根据返回的值(返回值为:OK或ERROR),如果为OK再把填入本地数据库。当时,想当然,觉得很简单,用js的xmlhttp ,如果根据response 的值是“OK”就执行提交本地数据库。很快写完发过去,让朋友试试,一试发现不行,后来一问,原来是跨域访问,我给忽略了,于是让朋友把asp改成web service,可朋友说程序是合作公司做的,只会asp,不会用web service ,狂晕ing。没办法,只能请出asp.net的 WebResponse了,很多网站采集程序都是用这个。第一版写完了,倒是可以跨域访问了,不过是乱码,调整有关编码的方式,终于可以了。这个应用虽小可是涉及的知识点不少:

1、xmlhttp 不能跨域提交。

当然XMLHttpRequest还是权宜的解决的方法,

2、webresponse可以进行跨域访问,不过要注意

1)、get和post的区别。
2)、注意Timeout的问题。

这些都是简单的程序,记下来备忘,高手就不必看了。

不废话了,下面是相关的c#代码:

 

 代码如下 复制代码
/// <summary>
        /// 使用Post方法发送数据
        /// </summary>
        /// <param name=”pi_strPostURl”>提交地址</param>
        /// <param name=”pi_strParm”>参数</param>
        /// <returns></returns>      
        public static string PostResponse(string pi_strPostURl, string pi_strParm)
        {
            try
            {
                //编码
                Encoding t_Encoding = Encoding.GetEncoding(“GB2312“);
        Uri t_Uri = new Uri(pi_strPostURl);             
                byte[] paramBytes = t_Encoding.GetBytes(pi_strParm);
                WebRequest t_WebRequest = WebRequest.Create(t_Uri);
        t_WebRequest.Timeout = 100000;
                //设置ContentType
                t_WebRequest.ContentType = “application/x-www-form-urlencoded“;
               
                t_WebRequest.Method = EnumMethod.POST.ToString();                //初始化
                using (Stream t_REStream = t_WebRequest.GetRequestStream())
                {
                    //发送数据
                    requestStream.Write(paramBytes, 0
, paramBytes.Length);
                }
               
                WebResponse t_WebResponse =
 t_WebRequest.GetResponse();
               
                using (StreamReader t_StreamReader = new StreamReader(t_WebResponse .GetResponseStream(), t_Encoding))
                {
                    return t_StreamReader.ReadToEnd();
                }
            }
            catch
            {
                return “ERROR“;
            }
        }
 
public static string GetResponse(string pi_strPostURl, string pi_strParm)
        {
            try
            {
                //编码
                Encoding t_Encoding = Encoding.GetEncoding(“GB2312“);              
                Uri t_Uri = new Uri(string.Format(“{0}?{1}“, pi_strPostURl, pi_strParm));
               
                WebRequest t_WebRequest =
 WebRequest.Create(t_Uri);
              
                t_WebRequest.Timeout = 100000;
                t_WebRequest.ContentType = “application/x-www-form-urlencoded“;
              
                t_WebRequest.Method = EnumMethod.GET.ToString(); 
                WebResponse t_WebResponse =
 t_WebRequest.GetResponse();
               
                using (StreamReader t_StreamReader = new StreamReader(t_WebResponse.GetResponseStream(), t_Encoding))
                {
                    return t_StreamReader.ReadToEnd();
                }
            }
            catch (Exception e)
            {
                return e.ToString();
            }
        }
public static string AtionResponse(string pi_Url, EnumMethod pi_Method)
        {
             string t_strUrlPath=“”;
             string t_parm = “”;           
             Uri  t_Url = new Uri(pi_Url);               
             t_parm= t_Url.Query;
             if (parmString.StartsWith(“?“))
                    t_parm = t_parm.Remove(0, 1);               
             t_strUrlPath = “http://“ + t_Url .Authority + t_Url .AbsolutePath;
            return GetResponse(t_strUrlPath, t_parm, pi_Method);
        }
 public enum EnumMethod
        {
            POST,
            GET
        }

现在jquery ajax支持跨域了,下面看个实例我们可对上面进行处理成json数据即可

JQuery.getJSON也同样支持jsonp的数据方式调用。

客户端JQuery.ajax的调用代码示例:

 代码如下 复制代码

$.ajax({
 type : "get",
 async:false,
 url : "http://www.xxx.com/ajax.do",
 dataType : "jsonp",
 jsonp: "callbackparam",//服务端用于接收callback调用的function名的参数
 jsonpCallback:"success_jsonpCallback",//callback的function名称
 success : function(json){
  alert(json);
  alert(json[0].name);
 },
 error:function(){
  alert('fail');
 }
});

服务端返回数据的示例代码:

 代码如下 复制代码
public void ProcessRequest (HttpContext context) {
 context.Response.ContentType = "text/plain";
 String callbackFunName = context.Request["callbackparam"];
 context.Response.Write(callbackFunName + "([ { name:"John"}])");
}

        而jquery.getScript方式处理的原理类似,也同样需要服务端返回数据上做支持,不同的是服务端返回的结果不同。不是返回一个callback的function调用,而是直接将结果赋值给请求传递的变量名。客户端则是像引入一个外部script一样加载返回的数据 来源:http://www.111cn.net/net/net/56393.htm

posted @ 2014-11-25 22:13  divor  阅读(808)  评论(0编辑  收藏  举报