Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading the BitBucket API with Authentication for a Private Repository in C#.net

Tags:

c#

bitbucket

api

I've been trying for a few days to get the BitBucket API to work for me, but have come to a grinding halt when it comes to getting it to work for a private repository with authentication (with the issues set as private, when they're set to public and no authentication is needed it all works fine)

Code sample is as follows:

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

    }

Many thanks.

like image 817
Stephen Avatar asked Jul 14 '11 16:07

Stephen


1 Answers

I had the same problem recently, and I found two different solutions.

First, vanilla .net with HttpWebRequest and HttpWebResponse:
(this came from an answer here at Stack Overflow, but unfortunately I can't find the link anymore)

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

Or, if you want to do the same with less code, you can use 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;   

By the way, I decided to use the HttpWebRequest solution for my own application.
I'm writing a small tool to clone all my Bitbucket repositories (including the private ones) to my local machine. So I just make one single call to the Bitbucket API to get the list of repositories.
And I didn't want to include another library in my project just to save a few lines of code for this one single call.

like image 180
Christian Specht Avatar answered Sep 23 '22 02:09

Christian Specht