C#带cookie发送http请求,http请求带cookie

本文介绍了如何通过设置登录Session Cookie,调用特定接口(http://10.199.22.112/readPlan/queryPlan)来请求数据,包括请求头设置、Cookie管理及异常处理过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/// <summary>
/// 请求(正在计划)的接口数据
/// </summary>
private static void GetData(string loginSessionCookie)
{
 
	//所有段
	string url = "http://10.199.22.112/readPlan/queryPlan?start=1&limit=9999&startDate=2021-10-29";
	string backMsg = "";
	try
	{
		System.Net.HttpWebRequest httpRquest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
		httpRquest.Method = "GET";

		httpRquest.KeepAlive = true;
		httpRquest.AllowAutoRedirect = false;
		httpRquest.Accept = "*/*";
		httpRquest.Referer = "http://10.199.22.112/plan/getPlan";

		//这行代码很关键,不设置ContentType将导致后台参数获取不到值
		httpRquest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";

		//byte[] dataArray = System.Text.Encoding.UTF8.GetBytes(sendData);
		//httpRquest.ContentLength = dataArray.Length;
		//System.IO.Stream requestStream = null;
		//if (string.IsNullOrWhiteSpace(sendData) == false)
		//{
		//    requestStream = httpRquest.GetRequestStream();
		//    requestStream.Write(dataArray, 0, dataArray.Length);
		//    requestStream.Close();
		//}

		// 设置cookie
		//浏览器参考值Cookie: SESSION=32dc4263-371e-440b-9a76-a44416584c73
		//loginSessionCookie值=32dc4263-371e-440b-9a76-a44416584c73
		var cookieContainer = new System.Net.CookieContainer();
		var cookie = new System.Net.Cookie("SESSION", loginSessionCookie); 
		cookie.Domain = httpRquest.Host;          
		cookieContainer.Add(cookie);
		httpRquest.CookieContainer = cookieContainer;
		 
		Console.WriteLine("Cookie已经设置");

		System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)httpRquest.GetResponse();

		// response.ContentType = "application/json;charset=UTF-8";
		System.IO.Stream responseStream = response.GetResponseStream();
		System.IO.StreamReader reader = new System.IO.StreamReader(responseStream, System.Text.Encoding.UTF8);
		backMsg = reader.ReadToEnd();
		Console.WriteLine(backMsg);
		LogHelpter.AddLog(backMsg);

		reader.Close();
		reader.Dispose();
		//requestStream?.Dispose();
		responseStream.Close();
		responseStream.Dispose();
		Console.WriteLine("获取数据成功");
	}
	catch (Exception ex)
	{
		Console.WriteLine("拉取数据异常:" + ex.ToString());
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王焜棟琦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值