Python Request/cURL to C# POST request



我需要帮助,向论坛发出简单的 POST 请求。我有正确的数据,当我编写为 cURL 命令并使用 GitBash 运行它时,它也在 Python 中工作。问题是这在 C# 中不起作用。

我需要

你的帮助,因为我不知道如何在我需要的 C# 中编写正确的代码。

这是一个Python代码:

import requests
headers = {
    'Content-type': 'application/x-www-form-urlencoded',
    'Cookie': 'cookie_notice=1'
}
data = 'id=44&typ=0&parent=-1&login=User&password=password&text=test22ntest33'
response = requests.post('address.php', headers=headers, data=data)

这是一个网址:

curl 'address.php' -H 'Content-Type: application/x-www-form-urlencoded' -H 'Cookie: cookie_notice=1' -d "id=44&typ=0&parent=-1&login=User&heslo=password&text=test22"

我尝试用这个编译:https://curl.olsh.me/

using (var httpClient = new HttpClient())
{
    using (var request = new HttpRequestMessage(new HttpMethod("POST"), "http://address.php/"))
    {
        request.Headers.TryAddWithoutValidation("Cookie", "cookie_notice=1"); 
        request.Content = new StringContent("id=44&typ=0&parent=-1&login=User&heslo=password&text=test22", Encoding.UTF8, "application/x-www-form-urlencoded"); 
        var response = await httpClient.SendAsync(request);
    }
}

该程序运行此 C# 代码没有任何错误,但在讨论论坛中不是我的贡献。

感谢您的回答!

问题是HttpClient忽略了请求Cookie标头,因为它依赖于HttpClientHandler及其CookieContainer。该解决方案告诉HttpClient您将通过标头设置 cookie

var httpClient = new HttpClient(new HttpClientHandler { UseCookies = false }))

最新更新