一聚教程网:一个值得你收藏的教程网站

热门教程

asp.net中WebRequest Post 及Get 数据实例

时间:2022-06-25 03:54:29 编辑:袖梨 来源:一聚教程网

sqlserver/42852.htm target=_blank >
 代码如下 复制代码

 

public class WebRequestHelper
     {
         ///


         /// 以POST 形式请求数据
         ///

         ///
         ///
         ///
       public  static string PostData(string RequestPara,string Url)
         {
             WebRequest hr = HttpWebRequest.Create(Url);
 
             byte[] buf = System.Text.Encoding.GetEncoding("utf-8").GetBytes(RequestPara);
             hr.ContentType = "application/x-www-form-urlencoded";
             hr.ContentLength = buf.Length;
             hr.Method = "POST";
 
             System.IO.Stream RequestStream = hr.GetRequestStream();
             RequestStream.Write(buf, 0, buf.Length);
             RequestStream.Close();
 
             System.Net.WebResponse response = hr.GetResponse();
             StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));
             string ReturnVal = reader.ReadToEnd();
             reader.Close();           
             response.Close();
 
             return ReturnVal;
         }
 
         ///
         /// 以GET 形式获取数据
         ///

         ///
         ///
         ///
 
       public static  string GetData(string RequestPara, string Url)
         {
             RequestPara=RequestPara.IndexOf('?')>-1?(RequestPara):("?"+RequestPara);
 
             WebRequest hr = HttpWebRequest.Create(Url + RequestPara);
 
             byte[] buf = System.Text.Encoding.GetEncoding("utf-8").GetBytes(RequestPara);         
             hr.Method = "GET";
 
             System.Net.WebResponse response = hr.GetResponse();
             StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));
             string ReturnVal = reader.ReadToEnd();
             reader.Close();
             response.Close();
 
             return ReturnVal;
         }
     }

热门栏目