首页 > Windows开发 > 详细

C# HttpWebRequest 添加Cookie验证

时间:2020-09-29 08:53:01      阅读:135      评论:0      收藏:0      [点我收藏+]

public static void Post3()
{
CookieContainer cookies = new CookieContainer();

string RequestPara = "account=win&password=123";
RequestPara = Regex.Replace(RequestPara, "%", "%25");
byte[] buf = System.Text.Encoding.GetEncoding("utf-8").GetBytes(RequestPara);

string url = "http:";
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
myHttpWebRequest.Method = "POST";
myHttpWebRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
myHttpWebRequest.ContentLength = buf.Length;
myHttpWebRequest.Timeout = 20 * 1000; //连接超时
myHttpWebRequest.Accept = "*/*";
myHttpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0;)";
myHttpWebRequest.CookieContainer = new CookieContainer(); //暂存到新实例

System.IO.Stream RequestStream = myHttpWebRequest.GetRequestStream();
RequestStream.Write(buf, 0, buf.Length);
RequestStream.Close();

 

HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
cookies = myHttpWebRequest.CookieContainer; //保存cookies
string cookiesstr = myHttpWebRequest.CookieContainer.GetCookieHeader(myHttpWebRequest.RequestUri); //把cookies转换成字符串

Console.WriteLine(cookiesstr);

 

 

 

 

 

//string data = "patient_name=测试"
// + "&patient_gender="
// + "&patient_sensibiligen="
// + "&patient_address="
// + "&patient_phone="
// + "&idcard="
// + "&doctor_rxnote_js="
// + "&ans_id=" + ApplicationCOM.Uid
// + "&patient_note="
// + "&ds_sign_id=";
//data = Regex.Replace(data, "%", "%25");
//buf = System.Text.Encoding.GetEncoding("utf-8").GetBytes(data);

url = "http:";
myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
//myHttpWebRequest.Method = "POST";

myHttpWebRequest.Method = "GET";

myHttpWebRequest.ContentLength = buf.Length;
myHttpWebRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
myHttpWebRequest.Timeout = 20 * 1000; //连接超时
myHttpWebRequest.Accept = "*/*";
myHttpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0;)";
myHttpWebRequest.Headers.Add("Cookie", cookiesstr);

//RequestStream = myHttpWebRequest.GetRequestStream();
//RequestStream.Write(buf, 0, buf.Length);
//RequestStream.Close();

myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();


Stream stream = myHttpWebResponse.GetResponseStream();
stream.ReadTimeout = 15 * 1000; //读取超时
StreamReader sr = new StreamReader(stream, Encoding.GetEncoding("utf-8"));
string strWebData = sr.ReadToEnd();
Console.WriteLine(strWebData);
}

C# HttpWebRequest 添加Cookie验证

原文:https://www.cnblogs.com/-jingzhe/p/13747894.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!