使用C#代碼模擬web請求,是一種常用的方法,以前沒專門整理過,這裡暫時貼上自己整理的完整代碼,以後再做梳理: ...
使用C#代碼模擬web請求,是一種常用的方法,以前沒專門整理過,這裡暫時貼上自己整理的完整代碼,以後再做梳理:
public class MyRequest { #region 輔助方法 public static string HttpGet(string url) { var request = (HttpWebRequest)WebRequest.Create(url); var response = (HttpWebResponse)request.GetResponse(); var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); return responseString; } /// <summary> /// httpPost請求--參數為object /// </summary> /// <param name="url">地址</param> /// <param name="postObject">Post參數傳輸為對象</param> /// <returns></returns> public static string HttpPost(string url, object postObject, string at = "", string rt = "") { string result = string.Empty; try { var request = (HttpWebRequest)WebRequest.Create(url); var postData = JsonConvert.SerializeObject(postObject); var data = Encoding.UTF8.GetBytes(postData); //uft-8支持中文 request.Method = "POST"; //request.ContentType = "application/x-www-form-urlencoded"; request.ContentType = "application/json;charset=UTF-8"; //request.ContentLength = data.Length; //這裡使用了coolie容器,用來模擬向伺服器發送cookie信息 CookieContainer zl_Cookie = new CookieContainer(); zl_Cookie.Add(new Cookie("at", at, "/", ".zhaopin.com")); zl_Cookie.Add(new Cookie("rt", rt, "/", ".zhaopin.com")); request.CookieContainer = zl_Cookie; using (var stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); result = new StreamReader(response.GetResponseStream()).ReadToEnd(); } catch (Exception ex) { result = ex.Message; } //Console.WriteLine("發送消息結果:" + result); return result; } /// <summary> /// httpPost請求--參數為string /// </summary> /// <param name="url">地址</param> /// <param name="postString">post參數參數為字元串</param> /// <returns></returns> public static string HttpPost(string url, string postString) { string result = string.Empty; try { var request = (HttpWebRequest)WebRequest.Create(url); var data = Encoding.UTF8.GetBytes(postString); //uft-8支持中文 request.Method = "POST"; //request.ContentType = "application/x-www-form-urlencoded"; request.ContentType = "application/json;charset=UTF-8"; request.ContentLength = data.Length; using (var stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); result = new StreamReader(response.GetResponseStream()).ReadToEnd(); } catch (Exception ex) { result = ex.Message; Console.WriteLine("同步簽到大屏發送消息error:" + result); } return result; } #endregion }