码迷,mamicode.com
首页 > Windows程序 > 详细

C# 发送Http协议 模拟 Post Get请求

时间:2017-09-01 19:40:15      阅读:269      评论:0      收藏:0      [点我收藏+]

标签:amr   form   method   ade   stat   str   发送   enc   参数   

1.参数 paramsValue的格式 要和 Reques.ContentType一致,

如果 contentype  "application/x-www-form-urlencoded" 表单类型,那么  参数为   a=1&b=2 形式

如果 。。。         "application/json"  json 类型  那么参数就为  "{a:1,b:2}" 格式

 

2.可以添加自定义header,  add(key,value)

接受获取header   Request.Headers.Get(key)

 

Get

public static string HttpGet(string url)
       { 
           string result=string.Empty;
           try
           {
               HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(url);
               wbRequest.Method = "GET";
               HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse();
               using (Stream responseStream = wbResponse.GetResponseStream())
               {
                   using (StreamReader sReader = new StreamReader(responseStream))
                   {
                       result = sReader.ReadToEnd();
                   }
               }
           }
           catch (Exception ex)
           { 
           
           }
           return result;
       }

Post 请求

public static string HttpPost(string url, string paramData, Dictionary<string, string> headerDic = null)
       {
           string result = string.Empty;
           try
           {
               HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(url);
               wbRequest.Method = "POST";
               wbRequest.ContentType = "application/x-www-form-urlencoded";
               wbRequest.ContentLength = Encoding.UTF8.GetByteCount(paramData);
               if (headerDic != null && headerDic.Count > 0)
               {
                   foreach (var item in headerDic)
                   {
                       wbRequest.Headers.Add(item.Key, item.Value);
                   }
               }
               using (Stream requestStream = wbRequest.GetRequestStream())
               {
                   using (StreamWriter swrite = new StreamWriter(requestStream))
                   {
                       swrite.Write(paramData);
                   }
               }
               HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse();
               using (Stream responseStream = wbResponse.GetResponseStream())
               {
                   using (StreamReader sread = new StreamReader(responseStream))
                   {
                       result = sread.ReadToEnd();
                   }
               }
           }
           catch (Exception ex)
           { }
         
           return result;
       }

C# 发送Http协议 模拟 Post Get请求

标签:amr   form   method   ade   stat   str   发送   enc   参数   

原文地址:http://www.cnblogs.com/duanbiflying/p/7464713.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!