使用HttpWebRequest发送登录详细信息

时间:2014-01-27 19:25:22

标签: c# httpwebrequest

我试图让这段代码暂停/取消暂停我的XBMC播放器

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(baseUrl+playPause);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
Debug.WriteLine(resStream);

我需要发送我的登录数据,让我们说MyUsernameSuperPassword

如何在请求中添加该数据?我试过request.Headers.Add("Authorization", "MyUsername SuperPassword");,但我仍然从中得到401错误。

编辑:没关系,我想通了

String username = "MyUsername";
String password = "SuperPassword";
String encoded = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username + ":" + password));
request.Headers.Add("Authorization", "Basic " + encoded);

1 个答案:

答案 0 :(得分:0)

有一篇关于使用HttpWebRequest发送登录详细信息的精彩文章,链接为post link 如果您觉得兄弟,那么您也可以尝试使用webClient类来解决这个问题。例如:

var url = @"..."; 
            var mybar= new System.Collections.Specialized.NameValueCollection();
            mybar.Add("username", "username");
            mybar.Add("password", "password");
            var client = new System.Net.WebClient();
            var data = client.UploadValues(url, mybar);
            var res = System.Text.Encoding.ASCII.GetString(data);
            Console.WriteLine(res);
            Console.ReadLine();