WebResponse cross domain access instance code in ES0en. net

  • 2020-11-03 22:06:21
  • OfStack

Two days ago, a friend asked me to help him write a program: visit the page of asp in ES1en.net, submit the data to the other party's database, according to the return value (return value: OK or ERROR), if for OK then fill in the local database. At the time, of course, it was easy to take js's xmlhttp and commit to the local database if the value of response was "OK". Soon finished writing and sent to the past, let a friend try, 1 try to find no, then 1 asked, the original is cross-domain access, I ignored, so let a friend to change asp service web, but the friend said that the program is done by the cooperation company, only asp, web service, ing crazy dizzy. There is no way, only asp. net WebResponse, which is used by many web capture programs. The first version of the written, but can be cross-domain access, but is a mess of code, adjust the way the code, finally can be. This is a small application that involves a lot of things:

1. xmlhttp cannot be committed across domains.

XMLHttpRequest, of course, is a stopgap solution,

2. webresponse can be accessed across domains, but be careful

1) The difference between get and post.
2) Pay attention to the problems of Timeout.

These are simple procedures, write down the notes, the master does not have to look.

Without further ado, here is the relevant c# code:


/// <summary>
        ///  use Post Method send data 
        /// </summary>
        /// <param name= " pi_strPostURl " > Submit the address </param>
        /// <param name= " pi_strParm " > parameter </param>
        /// <returns></returns>       
        public static string PostResponse(string pi_strPostURl, string pi_strParm)
        {
            try
            {
                // coding 
                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;
                // Set up the ContentType
                t_WebRequest.ContentType =  " application/x-www-form-urlencoded " ;

                t_WebRequest.Method = EnumMethod.POST.ToString();                // Initialize the 
                using (Stream t_REStream = t_WebRequest.GetRequestStream())
                {
                    // To send data 
                    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
            {
                // coding 
                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
        }

Now that jquery ajax supports cross-domain, here is an example where we can process the above data into json data

JQuery. getJSON also supports jsonp data mode calls.

Example of calling code of client JQuery. ajax:


$.ajax({
 type : "get",
 async:false,
 url : "https://www.ofstack.com/ajax.do",
 dataType : "jsonp",
 jsonp: "callbackparam",// The server is used for receiving callback Of the call function The name of the parameter 
 jsonpCallback:"success_jsonpCallback",//callback the function The name of the 
 success : function(json){
  alert(json);
  alert(json[0].name);
 },
 error:function(){
  alert('fail');
 }
});

Sample code for server return data:


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

The principle of jquery.ES69en method is similar, and it also needs support on the returned data of the server side. The difference is that the returned results of the server side are different. Instead of returning an function call to callback, the result is assigned directly to the variable name passed by the request. The client loads the returned data as if it were an external script1.


Related articles: