質問

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?

役に立ちましたか?

解決

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

他のヒント

try this before get respond

myRequest.Credentials = new NetworkCredential(userName,passWord);
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top