0

我正在尝试像这样读取 JSON 数据流-

string Username = "username";
string Password = "password";

string BaseUrl = "url";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(BaseUrl);
request.Credentials = new NetworkCredential(Username, Password);
request.ContentType = "application/json; charset=utf-8";
request.Headers["Authorization"] = "Basic " + authInfo;

using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
    if (response.StatusCode != HttpStatusCode.OK) throw new Exception(string.Format("Server returned {0}\n {1}", response.StatusCode, response.ToString()));
    // Cheat and always expect utf-8
    string result = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8).ReadToEnd();

    richTextBox1.Text = result;

我不确定这是否是通过将用户名和密码作为字符串传递来获得身份验证的基本方法但是一次执行我得到以下错误 -

远程服务器返回错误:(406) Not Acceptable。

我怎样才能克服这个?

4

1 回答 1

2

尝试使用标头身份验证,而不是通过 NetworkCredentials 进行

public void SetBasicAuthHeader(WebRequest req, String userName, String userPassword)
{
  string authInfo = userName + ":" + userPassword;
  authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
  req.Headers["Authorization"] = "Basic " + authInfo;
}
于 2012-02-24T16:52:11.700 回答