我想用HttpClient在C#中复制以下代码。这是使用响应
中返回的相同cookie的php代码if($cookies) {
curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__). '/cookies.txt');
} else {
curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__). '/cookies.txt');
}
到目前为止,我所做的是
var returnedCookies = response.Headers.GetValues("Set-Cookie").ToList();
然后将其用作
string newCookie = string.Join(";",returnedCookies);
client.DefaultRequestHeaders.Add("Cookie", newCookie);
我不明白为什么这不起作用,我也试过使用CookieContainer
,但它不起作用。有关此问题的任何帮助,或cURL
C#
使用的任何包装器或库都可以使用{I}}。
答案 0 :(得分:0)
看看LibCurlNet https://github.com/pjquirk/libcurl.NET
它有一些非常好的示例,您实际上可以使用c#
发送卷曲请求public void sendCurlRequest(string url, bool post, string post_aata, bool cookies)
{
try
{
Curl.GlobalInit((int)CURLinitFlag.CURL_GLOBAL_ALL);
Easy easy = new Easy();
Easy.WriteFunction wf = new Easy.WriteFunction(OnWriteData);
string writingData = string.Empty;
easy.SetOpt(CURLoption.CURLOPT_URL, instagramUrl + url);
easy.SetOpt(CURLoption.CURLOPT_FOLLOWLOCATION, 1);
easy.SetOpt(CURLoption.CURLOPT_SSL_VERIFYPEER, 0);
easy.SetOpt(CURLoption.CURLOPT_SSL_VERIFYHOST, 0);
if (post)
{
easy.SetOpt(CURLoption.CURLOPT_POST, 1);
File.WriteAllText("D:\\cookies\\post_data.txt", System.Web.HttpUtility.UrlEncode(post_aata));
easy.SetOpt(CURLoption.CURLOPT_POSTFIELDS, post_aata);
}
if (cookies)
{
easy.SetOpt(CURLoption.CURLOPT_COOKIEFILE, "\cookies.txt");
}
else
{
easy.SetOpt(CURLoption.CURLOPT_COOKIEJAR, "cookies.txt");
}
var c = easy.Perform();
int info = 0;
CURLcode code = easy.GetInfo(CURLINFO.CURLINFO_RESPONSE_CODE, ref info);
easy.Cleanup();
Curl.GlobalCleanup();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}