簡體   English   中英

在C#中使用https進行HttpWebRequest

[英]HttpWebRequest with https in C#

這段代碼不起作用; 它登錄到使用https協議的網站。 如何解決這個問題呢? 代碼在GetRequestStream()隨時隨地停止,表示協議違規異常未處理。

string username = "user";
string password = "pass";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://moje.azet.sk/prihlasenie.phtml?KDE=www.azet.sk%2Findex.phtml%3F");
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705)";

Console.WriteLine(request.GetRequestStream());

using (StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII))
{
    writer.Write("nick=" + username + "&password=" + password);
}

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//Retrieve your cookie that id's your session
//response.Cookies

using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
    Console.WriteLine(reader.ReadToEnd());
}

在調用GetRequestStream之前設置要發布的請求方法

喜歡

request.Method = "POST";

using (StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII))
{
    writer.Write("nick=" + username + "&password=" + password);
}

我的猜測是,您遇到的問題是由於(正如其他人已經建議的那樣)您正在執行GET請求而不是POST請求。 另外,我注意到該頁面上密碼字段的實際名稱是“heslo”而不是“密碼”。 此錯字不會導致Web服務器不返回響應,但它將導致其他問題,因為服務器正在查找要使用密碼值發布的特定變量名稱。

您可能還想預先確定要發布的內容的總長度,並將其設置為請求的ContentLength。 請參閱MSDN

當在HttpWebRequest類上設置的屬性發生沖突時,會拋出ProtocolViolationException。 如果應用程序將ContentLength屬性和SendChunked屬性設置為true,然后發送HTTP GET請求,則會發生此異常。 如果應用程序嘗試將chunked發送到僅支持HTTP 1.0協議的服務器(不支持此功能),則會發生此異常。 如果應用程序嘗試在未設置ContentLength屬性的情況下發送數據,或者在禁用緩沖並且在keepalive連接上(KeepAlive屬性為true),SendChunked為false, 則會發生此異常

這對我有用:

    var request = WebRequest.Create(_url);
    request.PreAuthenticate = true;
    request.Credentials = new NetworkCredential(_userName, _password);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM