Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpWebRequest with https in C#

This piece of code doesn't work; it's logging in into website which is using https protocol. How to solve this problem? The code stops at GetRequestStream() anytime anywhere saying that protocol violation exception is unhandled..

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());
}
like image 830
Skuta Avatar asked Feb 12 '09 16:02

Skuta


People also ask

What is the use of HttpWebRequest in c#?

The HttpWebRequest class provides support for the properties and methods defined in WebRequest and for additional properties and methods that enable the user to interact directly with servers using HTTP.

What is the difference between HttpWebRequest and WebRequest?

WebRequest is an abstract class. The HttpWebRequest class allows you to programmatically make web requests to the HTTP server.

Is HttpWebRequest disposable?

According to latest documentation, HttpWebRequest and WebRequest do not implement IDisposable.


1 Answers

Set request method to post, before calling GetRequestStream

like

request.Method = "POST";

using (StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII))
{
    writer.Write("nick=" + username + "&password=" + password);
}
like image 99
Ramesh Avatar answered Oct 08 '22 17:10

Ramesh