使用C#.net中的私有存储库的身份validation读取BitBucket API

我已经尝试了几天让BitBucket API为我工作,但是当它使用于具有身份validation的私有存储库(将问题设置为私有,当他们发现时)已经停止了’设置为公开,不需要身份validation,一切正常)

代码示例如下:

static void Main(string[] args) { WebProxy prox = new WebProxy("ProxyGoesHere"); prox.Credentials = CredentialCache.DefaultNetworkCredentials; var address = "repositories/UserFoo/SlugBar/issues/1"; var repCred = new CredentialCache(); repCred.Add(new Uri("https://api.bitbucket.org/"), "Basic", new NetworkCredential("UserFoo", "PassBar")); WebClient client = new WebClient(); client.Credentials = repCred; client.Proxy = prox; client.BaseAddress = "https://api.bitbucket.org/1.0/"; client.UseDefaultCredentials = false; client.QueryString.Add("format", "xml"); Console.WriteLine(client.DownloadString(address)); Console.ReadLine(); } 

非常感谢。

我最近遇到了同样的问题,我找到了两种不同的解决方案。

首先,带有HttpWebRequestHttpWebResponse vanilla .net:
(这来自Stack Overflow的答案,但不幸的是我找不到链接了)

 string url = "https://api.bitbucket.org/1.0/repositories/your_username/your_repo/issues/1"; var request = WebRequest.Create(url) as HttpWebRequest; string credentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes("your_username" + ":" + "your_password")); request.Headers.Add("Authorization", "Basic " + credentials); using (var response = request.GetResponse() as HttpWebResponse) { var reader = new StreamReader(response.GetResponseStream()); string json = reader.ReadToEnd(); } 

或者,如果您想使用更少的代码执行相同操作,则可以使用RestSharp :

 var client = new RestClient("https://api.bitbucket.org/1.0/"); client.Authenticator = new HttpBasicAuthenticator("your_username", "your_password"); var request = new RestRequest("repositories/your_username/your_repo/issues/1"); RestResponse response = client.Execute(request); string json = response.Content; 

顺便说一下,我决定将 HttpWebRequest 解决方案用于我自己的应用程序。
我正在编写一个小工具来将我的所有Bitbucket存储库(包括私有存储库)克隆到我的本地计算机上。 所以我只需要一次调用Bitbucket API来获取存储库列表。
而且我不想在我的项目中包含另一个库,只是为了一次调用保存几行代码。

使用WebClient仍然是可能的,你只需要像在Christian Specht的回答中那样手动创建Authorization标题:

 string credentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes("your_username" + ":" + "your_password")); client.Headers[ HttpRequestHeader.Authorization ] = "Basic " + credentials);