Rest Client Authorization错误

时间:2017-10-12 11:13:33

标签: c# .net httpwebrequest unauthorized

我想通过基本授权呼叫休息客户端。我试过这个,但在c#中有一个未经授权的(401)例外:

HttpWebRequest client = (HttpWebRequest)WebRequest.Create("http://someurl.com");
            client.Method = "POST";
            client.UseDefaultCredentials = true;
            var encoding = new UTF8Encoding();
            var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(mailinglist.ToString());
            client.ContentLength = bytes.Length;
            using (var writeStream = client.GetRequestStream())
            {
                writeStream.Write(bytes, 0, bytes.Length);
            }
            client.ContentType = "application/json";
            NetworkCredential nc = new NetworkCredential("8ec5f23e-18ba-4154-9962-7ebefeb027c0", "");
            //string credentials = String.Format("{0}:{1}", "8ec5f23e-18ba-4154-9962-7ebefeb027c0", "");
            //byte[] bts = Encoding.ASCII.GetBytes(credentials);
            //string base64 = Convert.ToBase64String(bts);
            client.PreAuthenticate = true;
            //string authorization = String.Concat("Basic ", base64);
            //Utils.WriteLog("Addaudience", authorization);
            //client.Headers.Add(HttpRequestHeader.Authorization, authorization);
            client.Credentials = nc;
            client.Accept = "application/json";

            using (var response = (HttpWebResponse)client.GetResponse())
            {
                var responseValue = string.Empty;

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
                    
                    throw new ApplicationException(message);
                }

                // grab the response
                using (var responseStream = response.GetResponseStream())
                {
                    if (responseStream != null)
                        using (var reader = new StreamReader(responseStream))
                        {
                            responseValue = reader.ReadToEnd();
                        }
                }
            }

请帮帮我,告诉我我的错误是什么?我还尝试将Authorization字符串放在标题中但不起作用。

感谢。

0 个答案:

没有答案