Frage

I am trying to read a JSON stream of data like so-

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;

I'm not sure if this is the basic way to gain authentication by passing in the username and password in as strings however one execution I get the following error-

The remote server returned an error: (406) Not Acceptable.

How can I get past this?

War es hilfreich?

Lösung

Try a header authentication instead of doing by 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;
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top