C# 发送Http协议 模拟 Post Get请求
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)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public static string HttpGet(string url) 2 { 3 string result=string.Empty; 4 try 5 { 6 HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(url); 7 wbRequest.Method = "GET"; 8 HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse(); 9 using (Stream responseStream = wbResponse.GetResponseStream()) 10 { 11 using (StreamReader sReader = new StreamReader(responseStream)) 12 { 13 result = sReader.ReadToEnd(); 14 } 15 } 16 } 17 catch (Exception ex) 18 { 19 20 } 21 return result; 22 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public static string HttpPost(string url, string paramData, Dictionary<string, string> headerDic = null) 2 { 3 string result = string.Empty; 4 try 5 { 6 HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(url); 7 wbRequest.Method = "POST"; 8 wbRequest.ContentType = "application/x-www-form-urlencoded"; 9 wbRequest.ContentLength = Encoding.UTF8.GetByteCount(paramData); 10 if (headerDic != null && headerDic.Count > 0) 11 { 12 foreach (var item in headerDic) 13 { 14 wbRequest.Headers.Add(item.Key, item.Value); 15 } 16 } 17 using (Stream requestStream = wbRequest.GetRequestStream()) 18 { 19 using (StreamWriter swrite = new StreamWriter(requestStream)) 20 { 21 swrite.Write(paramData); 22 } 23 } 24 HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse(); 25 using (Stream responseStream = wbResponse.GetResponseStream()) 26 { 27 using (StreamReader sread = new StreamReader(responseStream)) 28 { 29 result = sread.ReadToEnd(); 30 } 31 } 32 } 33 catch (Exception ex) 34 { } 35 36 return result; 37 }