使用WebRequest将参数和数据POST到TestFlight

时间:2012-05-08 16:43:54

标签: c# .net http testflight

我正在尝试使用TestFlight的上传API来自动化构建。这是他们的文档:https://testflightapp.com/api/doc/

这是我测试过并且有效的极简主义curl命令行请求:

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

我尝试将其转换为C#,如下所示:

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

不幸的是,在GetResponse(),我收到(500) Internal Server Error,而且没有更多信息。

我不确定我的postParameters中的数据是否应该被'包裹 - 我已经尝试过两种方式。我也不知道我的内容类型是否正确。我也试过application/x-www-form-urlencoded,但没有任何效果。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

感谢Adrian Iftode的评论,我找到了RestSharp,这让我可以像这样实施请求:

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

如果您正在制作UI应用程序,RestSharp也可以执行异步执行。查看上面链接中的文档!