C# 發送Http協議 模擬 Post Get請求
阿新 • • 發佈:2017-09-01
head log cnblogs cep bsp empty read ram color
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(stringurl) { 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請求