Sending requests to a website is pretty easy with http. Https is simple as well, but there are some things that you are going to have to look out for. One of the first things that you will need is a NetworkCredential object to identify yourself.
NetworkCredential cred=new NetworkCredential("daeron", "mypassword");
I wouldn't recommend hardcoding the user or password, but this is for demo purposes ;).
Of course, you'll need to add the System.Net namespace and a reference to the dll.
using System.Net;
You create a webrequest (HttpWebRequest provides more http, https functionality):
HttpWebRequest request = (HttpWebRequest)WebRequest.Create (https://www.mydomain.com/);
request.Credentials = new NetworkCredential("daeron", "mypassword");
Finally, you get the response:
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
One hang up you will run into if the webserver is using Windows Integrated Authentication and you are not on that server's domain or one that the domain has trust with. You may get 401 unauthorized errors. Your fix? use UnsafeAuthenticatedConnection Sharing:
request.UnsafeAuthenticatedConnectionSharing = true;
This maintains the NTLMAuthenticated connection between requests. One thing to keep an eye out for is ensuring that you know exactly when this is used as it can be used to as it could potentially be used to connect to resources when the user is not authenticated. Make sure that you have checks before this request is called.
The full code is below:
using System;
using System.Net;
namespace HttpsDemo
{
class Program
{
static void Main(string[] args)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.mydomain.com");
request.Credentials = new NetworkCredential("daeron", "mypassword");
request.UnsafeAuthenticatedConnectionSharing = true;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
string s = sr.ReadToEnd();
sr.Close();
Console.WriteLine(s);
}
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment