C#带cookie发送http请求,http请求带cookie
Posted 棉晗榜
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#带cookie发送http请求,http请求带cookie相关的知识,希望对你有一定的参考价值。
/// <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);
cookieContainer.Add(new Uri("http://10.199.22.112"),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());
}
}
以上是关于C#带cookie发送http请求,http请求带cookie的主要内容,如果未能解决你的问题,请参考以下文章