首页 > 解决方案 > Python 请求/cURL 到 C# POST 请求

问题描述

我需要对讨论论坛的简单 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=test22\ntest33'

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# 代码没有任何错误,但在讨论论坛中不是我的贡献。

感谢你的回答 !

标签: c#pythoncurlpost

解决方案


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

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

推荐阅读