2

I'm trying to connect to my router "panel" (192.168.1.1) using a simple C# HTTP Web Request:

var userName = "admin";
var passWord = "admin";
var encoding = new ASCIIEncoding();
var postData = "" + userName;
postData += (":" + passWord); //I saw (using Wireshark) that the HTTP packet is sending the username & password in this form: "username:password"
byte[] data = encoding.GetBytes(postData);

var myRequest = (HttpWebRequest)WebRequest.Create("http://192.168.1.1");
myRequest.Method = "POST"; **//Or should I use GET?**
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
var newStream = myRequest.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
try
{
  var response = myRequest.GetResponse();
  var responseStream = response.GetResponseStream();
  var responseReader = new StreamReader(responseStream);
  var result = responseReader.ReadToEnd();
}
catch (WebException we)
{
  Console.WriteLine(we.Message);
}

When I'm running this code I get an saying '401 Not Authorized Exception', although the UN and Password are correct.

Can anyone suggest me, what's wrong here?

jimsweb
  • 1,082
  • 2
  • 17
  • 37
albeck
  • 510
  • 1
  • 7
  • 16

2 Answers2

3

Have you tried using this as the address and dropping the post data part of your code :

http://username:password@192.168.1.1

Else, you could use basic authentication, as explained in this article

Laurent S.
  • 6,816
  • 2
  • 28
  • 40
  • I tried this: `var myRequest = (HttpWebRequest)WebRequest.Create("http://admin:admin@192.168.2.1");` `myRequest.Method = "POST";` `myRequest.ContentType = "application/x-www-form-urlencoded";` `var response = myRequest.GetResponse();` `var responseStream = response.GetResponseStream();` `var responseReader = new StreamReader(responseStream);` `var result = responseReader.ReadToEnd();` but I still get an 401 Unauthorized Exception – albeck Jun 17 '13 at 09:58
  • i'm not sure you've got to POST this as you're doing, I think you should use basic authentication : http://grahamrhay.wordpress.com/2011/08/22/making-a-post-request-in-c-with-basic-authentication/ – Laurent S. Jun 17 '13 at 10:04
0

try this before get respond

myRequest.Credentials = new NetworkCredential(userName,passWord);