几天来,我一直在尝试让Bitbucket API为我工作,但当要让它为具有身份验证的私有存储库工作时(将问题设置为私有,当它们设置为公共且不需要身份验证时,一切正常),我就停了下来。
代码示例如下:

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();

    }

非常感谢。

最佳答案

我最近遇到了同样的问题,我找到了两种不同的解决方法。
首先,香草.net的HttpWebRequestHttpWebResponse
(这来自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就可以得到存储库列表。
我不想在我的项目中包含另一个库只是为了为这个调用保存几行代码。

07-25 23:34
查看更多