C#模拟httpwebrequest请求_向服务器模拟cookie发送
程序员文章站
2022-08-22 10:59:10
使用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 }
上一篇: 一加9rt怎么开启分屏?一加9rt打开分屏功能方法
下一篇: ASP.NET上传文件大小限制