我正在尝试读取像_-
这样的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。
我怎样才能超越这个?
答案 0 :(得分:1)
尝试使用标头身份验证,而不是使用NetworkCreddentials
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;
}