[英]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=test22\ntest33'
response = requests.post('address.php', headers=headers, data=data)
這是一個cURL:
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 }))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.