Search code examples
c#.nethttptestflight

Using WebRequest to POST parameters and data to TestFlight


I'm trying to TestFlight's upload API to automate builds. Here's their documentation: https://testflightapp.com/api/doc/

This is the minimalist curl command-line request that I've tested and had working:

.\curl.exe http://testflightapp.com/api/builds.json 
  -F file=@MyFileName.ipa
  -F api_token='myapitoken' -F team_token='myteamtoken' 
  -F notes='curl test'

I've tried converting that into C# like this:

var uploadRequest = WebRequest.Create("http://testflightapp.com/api/builds.json") as HttpWebRequest;
uploadRequest.Method = "POST";
uploadRequest.ContentType = "multipart/form-data";

var postParameters = string.Format("api_token={0}&team_token={1}&notes=autobuild&file=", TESTFLIGHT_API_TOKEN, TESTFLIGHT_TEAM_TOKEN);
var byteParameters = Encoding.UTF8.GetBytes(postParameters);

var ipaData = File.ReadAllBytes(IPA_PATH);

uploadRequest.ContentLength = byteParameters.Length + ipaData.Length;
var requestStream = uploadRequest.GetRequestStream();
requestStream.Write(byteParameters, 0, byteParameters.Length);
requestStream.Write(ipaData, 0, ipaData.Length);
requestStream.Close();

var uploadResponse = uploadRequest.GetResponse();

Unfortunately at GetResponse() I get a (500) Internal Server Error and no more info.

I'm not sure if the data in my postParameters should be wrapped by 's or not -- I've tried it both ways. I also don't know if my content type is right. I've also tried application/x-www-form-urlencoded but that didn't have any effect.

Any help greatly appreciated.


Solution

  • Thanks to Adrian Iftode's comment, I found RestSharp, which allowed me to implement the request like this:

    var testflight = new RestClient("http://testflightapp.com");
    
    var uploadRequest = new RestRequest("api/builds.json", Method.POST);
    
    uploadRequest.AddParameter("api_token", TESTFLIGHT_API_TOKEN);
    uploadRequest.AddParameter("team_token", TESTFLIGHT_TEAM_TOKEN);
    uploadRequest.AddParameter("notes", "autobuild");
    
    uploadRequest.AddFile("file", IPA_PATH);
    
    var response = testflight.Execute(uploadRequest);
    System.Diagnostics.Debug.Assert(response.StatusCode == HttpStatusCode.OK, 
                "Build not uploaded, testflight returned error " + response.StatusDescription);
    

    If you're making a UI app, RestSharp can also do asyncronous execution. Check the docs at the link above!