C#带参数发送http请求,接收返回cookie
Posted 棉晗榜
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#带参数发送http请求,接收返回cookie相关的知识,希望对你有一定的参考价值。
/// <summary>
/// 登录,返回获取到的cookie
/// </summary>
public static string Login()
{
string cookie_ck = string.Empty;
try
{
string url = "http://10.122.66.157/api/user/userLogin";
string sendData = "code=01&login=[\\"10.192.111.79\\",\\"hhs\\",\\"hhs\\"]&sql=[\\"lhd\\",\\"1234567qwe\\"]";
System.Net.HttpWebRequest httpRquest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
httpRquest.Method = "POST";
//获取response的cookie必须设置
httpRquest.CookieContainer = new System.Net.CookieContainer();
//string referer = "http://10.122.66.157/home/login.html";
//httpRquest.Headers.Add("Referer", referer);
//httpRquest.Headers.Add("Origin", "http://10.122.66.157");
//这行代码很关键,不设置ContentType将导致后台参数获取不到值
httpRquest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
System.IO.Stream requestStream = null;
if (!string.IsNullOrWhiteSpace(sendData))
{
byte[] dataArray = System.Text.Encoding.UTF8.GetBytes(sendData);
requestStream = httpRquest.GetRequestStream();
requestStream.Write(dataArray, 0, dataArray.Length);
requestStream.Close();
}
System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)httpRquest.GetResponse();
//返回的cookie
Console.WriteLine("返回的cookie:");
//response.Headers
var json = Newtonsoft.Json.JsonConvert.SerializeObject(response.Cookies);
Console.WriteLine(json);
foreach (System.Net.Cookie item in response.Cookies)
{
string cookie = item.Name + "=" + item.Value;
Console.WriteLine(cookie);
if (item.Name.Equals("JSESSIONID"))
{
Console.WriteLine("身份需要的cookie:" + item.Name);
cookie_ck = item.Value;
}
}
System.IO.Stream responseStream = response.GetResponseStream();
System.IO.StreamReader reader = new System.IO.StreamReader(responseStream, System.Text.Encoding.UTF8);
string backMsg = reader.ReadToEnd();
Console.WriteLine(backMsg);
reader.Close();
reader.Dispose();
requestStream?.Dispose();
responseStream.Close();
responseStream.Dispose();
}
catch (Exception ex)
{
Console.WriteLine("异常=" + ex.ToString());
}
return cookie_ck;
}
以上是关于C#带参数发送http请求,接收返回cookie的主要内容,如果未能解决你的问题,请参考以下文章