创建CURL请求ASP.NET

Tro*_*ven 2 php c# asp.net curl webrequest

curl -X POST 'https://api.twilio.com/2010-04-01/Accounts/AC053acaaf55d75ef32233132196e/Messages.json' \
--data-urlencode 'To=5555555555'  \
--data-urlencode 'From=+15555555555'  \
--data-urlencode 'Body=Test' \
-u AC053acaaf55d75a393498192382196e:[AuthToken]
Run Code Online (Sandbox Code Playgroud)

我有上面的卷曲代码,我需要连接到的API.问题是我需要使用ASP.NET(C#)进行连接.我对ASP.NET不是很熟悉,也不知道从哪里开始.我知道如何在PHP中编写代码,但ASP.NET是另一回事.从我所做的研究中我需要使用WebRequest.如何输入请求的发布数据和authtoken(-u AC053acaaf55d75a393498192382196e:[AuthToken])部分.

string url = "https://api.twilio.com/2010-04-01/Accounts/AC053acaaf55d75ef32233132196e/Messages.json";
WebRequest myReq = WebRequest.Create(url);
myReq.Method = "POST";
Run Code Online (Sandbox Code Playgroud)

Dev*_*der 5

Twilio福音传教士在这里.

为了确保我们在同一页面上,您需要在Twilio API中向theMessages端点发出POST请求,但是您不能使用我们的帮助程序库.

没问题,您可以使用.NET本机HTTP客户端库,HttpWebRequest和HttpWebResponse.多数民众赞同如下:

//Twilio Credentials
string accountsid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
string authtoken = "asdsadasdasdasdasdsadsaads";

//Twilio API url, putting your AccountSid in the URL
string urltemplate = "https://api.twilio.com/2010-04-01/Accounts/{0}/Messages.json";
string url = string.Format(urltemplate, accountsid);

//Create a basic authorization
string basicauthtoken = string.Format("Basic {0}", System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(accountsid + ":" + authtoken)));

//Build and format the HTTP POST data
string formencodeddata = "To=+15555555555&From=+15556666666&Body=Hello World";
byte[] formbytes = System.Text.ASCIIEncoding.Default.GetBytes(formencodeddata);

//Create a new HTTP request object, set the method to POST and write the POST data to it
var webrequest = (HttpWebRequest)WebRequest.CreateHttp(url);
webrequest.Method = "POST";
webrequest.ContentType = "application/x-www-form-urlencoded";
webrequest.Headers.Add("Authorization", basicauthtoken);

using (Stream postStream = webrequest.GetRequestStream()) {
    postStream.Write(formbytes, 0, formbytes.Length);
}

//Make the request, get a response and pull the data out of the response stream
var webresponse = (HttpWebResponse)webrequest.GetResponse();
Stream responseStream = webresponse.GetResponseStream();
var reader = new StreamReader(responseStream);

string result = reader.ReadToEnd();
Run Code Online (Sandbox Code Playgroud)

如果需要,还有GetRequestStream和GetResponse方法的异步版本.

希望有所帮助.