非常奇怪的错误401?

时间:2016-03-10 14:36:59

标签: c# api http-status-code-401

我收到401错误,我没有预料到。我100%确定密码和usernamne是正确的。当我在邮递员上尝试它时,它可以工作,我得到了我期望的数据。但在此代码中,.downloadstring()方法返回401错误。我创建了一个新的收获帐户,尝试使用相同的代码访问该帐户,只需更改密码和用户名,我就获得了我想要的API数据。有没有其他原因可以缓存错误的密码或用户名错误401?

public List<Project> GetAllProjects()
{
    uri = "https://bruh.harvestapp.com/projects";
    jsonPath = Path.Combine(HostingEnvironment.MapPath("~/App_Data"), "projects.json");

    using (WebClient webClient = new WebClient())
    {
        webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
        webClient.Headers[HttpRequestHeader.Accept] = "application/json";
        webClient.Headers[HttpRequestHeader.Authorization] = "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword));

        string response = webClient.DownloadString(uri);

        projectsList = JsonConvert.DeserializeObject<List<Wrapper>>(response).Select(p => p.project).ToList();
    }

    return projectsList;
}

1 个答案:

答案 0 :(得分:0)

根据收获的this C#代码示例,有一些事情需要改变:

static void Main(string[] args)
{
  HttpWebRequest request; 
  HttpWebResponse response = null; 
  StreamReader reader; 
  StringBuilder sbSource; 
  // 1. Set some variables specific to your account.
  string uri = "https://yoursubdomain.harvestapp.com/projects";
  string username="youremail@somewhere.com";
  string password="yourharvestpassword";
  string usernamePassword = username + ":" + password;

  ServicePointManager.ServerCertificateValidationCallback = Validator;

try
  { 
     request = WebRequest.Create(uri) as HttpWebRequest; 
     request.MaximumAutomaticRedirections = 1;
     request.AllowAutoRedirect = true;

     // 2. It's important that both the Accept and ContentType headers are
     // set in order for this to be interpreted as an API request.
     request.Accept = "application/xml"; 
     request.ContentType = "application/xml"; 
     request.UserAgent = "harvest_api_sample.cs";
     // 3. Add the Basic Authentication header with username/password string.
     request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));

     using (response = request.GetResponse() as HttpWebResponse) 
     { 
        if (request.HaveResponse == true && response != null) 
        { 
           reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
           sbSource = new StringBuilder(reader.ReadToEnd());
           // 4. Print out the XML of all projects for this account.
           Console.WriteLine(sbSource.ToString()); 
        } 
     } 
  }