c#httpwebrequest for basic authentication

时间:2016-06-28 18:46:22

标签: c# httpwebrequest basic-authentication

我一直在尝试使用用户名,密码和访问密钥在服务器上进行身份验证,以便我可以使用其API。我曾经遵循以下代码:

        string encoded = Convert.ToBase64String(Encoding.Default.GetBytes("myusername:mypass"));      
        string api = "blahblahblahblabh";
        string auth_string = "Basic " + encoded;
        string _post_string = "username=myusername&password=mypass&grant_type=password";
        HttpWebRequest request = WebRequest.Create(https_website) as HttpWebRequest;
        request.Accept = "application/xml";
        request.Method = "POST";            
        request.ContentType = "application/x-www-forms-urlencoded";
        request.ContentLength = _post_string.Length;
        CookieContainer cookies = new CookieContainer();
        request.CookieContainer = cookies;

        request.Headers["Authorization"] = auth_string;
        request.Headers["api-key"] = api;
        request.ServerCertificateValidationCallback += (sender1, certificate, chain, sslPolicyErrors) => { return true; };
        StreamWriter writer = new StreamWriter(request.GetRequestStream());
        writer.Write(_post_string);
        writer.Close();

        HttpWebResponse response = request.GetResponse() as HttpWebResponse;
        StreamReader reader = new StreamReader(response.GetResponseStream());

        string xml_response = reader.ReadToEnd();
        reader.Close();

所以我发送了一个带有用户名/密码和access_key的POST请求,并试图收到回复。我总是得到"远程服务器返回错误:(404)Not Found"。如果我在第一行的字符串中添加更多内容,例如,如果不是" myusername:mypass"我用" myusername:mypass:password"我收到错误401(未经授权)。我不明白为什么会这样......

0 个答案:

没有答案