一、Get 方式傳輸 二、POST 方式傳輸 其中PUT、DELETE方式跟上面基本相似。這裡就不再多說明 ...
一、Get 方式傳輸
//url為請求的網址,param參數為需要查詢的條件(服務端接收的參數,沒有則為null) //返回該次請求的響應 public string HttpGet(string url, Dictionary<String, String> param) { if (param != null) //有參數的情況下,拼接url { url = url + "?"; foreach (var item in param) { url = url + item.Key + "=" + item.Value + "&"; } url = url.Substring(0, url.Length - 1); } HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;//創建請求 request.Method = "GET"; //請求方法為GET HttpWebResponse res; //定義返回的response try { res = (HttpWebResponse)request.GetResponse(); //此處發送了請求並獲得響應 } catch (WebException ex) { res = (HttpWebResponse)ex.Response; } StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8); string content = sr.ReadToEnd(); //響應轉化為String字元串 return content; }
二、POST 方式傳輸
public static string HttpPost(string url, Dictionary<String, String> param) { HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; //創建請求 CookieContainer cookieContainer = new CookieContainer(); request.CookieContainer = cookieContainer; request.AllowAutoRedirect = true; //request.AllowReadStreamBuffering = true; request.MaximumResponseHeadersLength = 1024; request.Method = "POST"; //請求方式為post request.AllowAutoRedirect = true; request.MaximumResponseHeadersLength = 1024; request.ContentType = "application/json"; JObject json = new JObject(); if (param.Count != 0) //將參數添加到json對象中 { foreach (var item in param) { json.Add(item.Key, item.Value); } } string jsonstring = json.ToString();//獲得參數的json字元串 byte[] jsonbyte = Encoding.UTF8.GetBytes(jsonstring); Stream postStream = request.GetRequestStream(); postStream.Write(jsonbyte, 0, jsonbyte.Length); postStream.Close(); //發送請求並獲取相應回應數據 HttpWebResponse res; try { res = (HttpWebResponse)request.GetResponse(); } catch (WebException ex) { res = (HttpWebResponse)ex.Response; } StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8); string content = sr.ReadToEnd(); //獲得響應字元串 return content; }
其中PUT、DELETE方式跟上面基本相似。這裡就不再多說明