几天来我一直在尝试让 BitBucket API 为我工作,但是当涉及到让它为具有身份验证的私有(private)存储库工作时(将问题设置为私有(private)),我遇到了困难,当它们被设置为公开并且不需要身份验证时一切正常)
代码示例如下:
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();
}
非常感谢。
最佳答案
我最近遇到了同样的问题,我找到了两种不同的解决方案。
首先,带有 HttpWebRequest
和 HttpWebResponse
的 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 存储库(包括私有(private)存储库)克隆到我的本地计算机。因此,我只需对 Bitbucket API 进行一次调用即可获取存储库列表。
我不想在我的项目中包含另一个库,只是为了为这个单一调用节省几行代码。
关于c# - 在 C#.net 中读取带有私有(private)存储库身份验证的 BitBucket API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6696314/