使用C#发送Http 请求实现模拟登陆
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Security.Policy; using System.Text; namespace WindowsFormsApplication1 { public class PostLogin { public static string GetLogin() { string url = "http://***/Login"; string postData = "{\"UserName\":\"*******\",\"UserPassword\":\"************************\"}"; CookieContainer cookie = GetCookie(postData, url);
string result = GetContent(cookie, "http://www.*****.com"); return result; } public static CookieContainer GetCookie(string postString, string postUrl) { CookieContainer cookie = new CookieContainer(); HttpWebRequest httpRequset = (HttpWebRequest)HttpWebRequest.Create(postUrl);//创建http 请求 httpRequset.CookieContainer = cookie;//设置cookie httpRequset.Method = "POST";//POST 提交 httpRequset.Headers["RTSToken"] = "************************"; httpRequset.Host = "wwww.****.com"; httpRequset.KeepAlive = true; httpRequset.Headers["Origin"] = "www.***.com"; httpRequset.Headers["Accept-Encoding"] = "gzip, deflate"; httpRequset.Headers["Accept-Language"] = "zh-CN,zh;q=0.9"; httpRequset.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36"; httpRequset.Accept = "application/json, text/javascript, */*; q=0.01"; httpRequset.ContentType = "application/json";//以上信息在监听请求的时候都有的直接复制过来 byte[] bytes = System.Text.Encoding.UTF8.GetBytes(postString); httpRequset.ContentLength = bytes.Length; Stream stream = httpRequset.GetRequestStream(); stream.Write(bytes, 0, bytes.Length); stream.Close();//以上是POST数据的写入 HttpWebResponse httpResponse = (HttpWebResponse)httpRequset.GetResponse();//获得服务端响应 return cookie;//拿到cookie } static string GetContent(CookieContainer cookie, string url) { string content; HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(url); httpRequest.CookieContainer = cookie; httpRequest.Referer = url; httpRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko"; httpRequest.Accept = "text/html, application/xhtml+xml, */*"; httpRequest.ContentType = "application/x-www-form-urlencoded"; httpRequest.Method = "GET"; HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse(); using (Stream responsestream = httpResponse.GetResponseStream()) { using (StreamReader sr = new StreamReader(responsestream, System.Text.Encoding.UTF8)) { content = sr.ReadToEnd(); } } return content; } } }