using System.Net.Http.Headers;
using System.Text;
const string accountSid = "ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
const string messageSid = "MMxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
const string mediaSid = "MExxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
var mediaUrl = $"https://api.twilio.com/2010-04-01/Accounts/{accountSid}/Messages/{messageSid}/Media/{mediaSid}";
const string localFilePath = "image.jpg";
using var httpClient = new HttpClient();
using var httpRequest = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri(mediaUrl)
};
const bool useBasicAuth = true;
if (useBasicAuth)
{
var authToken = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");
var authHeaderValue = $"{accountSid}:{authToken}";
authHeaderValue = Convert.ToBase64String(Encoding.ASCII.GetBytes(authHeaderValue));
httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Basic", authHeaderValue);
}
using var response = await httpClient.SendAsync(httpRequest);
if (!response.IsSuccessStatusCode)
{
Console.WriteLine($"HTTP Status Code: {response.StatusCode}");
Console.WriteLine($"Response body: {await response.Content.ReadAsStringAsync()}");
return;
}
await using var fileStream = new FileStream(localFilePath, FileMode.CreateNew);
await response.Content.CopyToAsync(fileStream);
1条答案
按热度按时间vltsax251#
Twilio SDK可以帮助你定位彩信的media,媒体信息也会传递给你的webhook处理程序,但是SDK没有任何类/方法来帮助你下载媒体文件。
默认情况下,如果您知道URL,则可以公开访问该文件,并且不需要验证。您可以enable basic auth for your MMS media files,这样只有您可以通过使用帐户SID和验证令牌或API Key SID and API Key Secret进行验证来下载它们。
下面是一个C#示例,说明如何在使用和不使用基本身份验证的情况下下载文件: