7

I'm trying to download a composition media file into my hard drive using the following code:

try
{
    var uri = "https://video.twilio.com/v1/Compositions/" + sid + "/Media?Ttl=6000";

    var request = (HttpWebRequest)WebRequest.Create(uri);
    request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(_apiKeySid + ":" + _apiKeySecret)));
    request.AllowAutoRedirect = false;
    var responseBody = new StreamReader(request.GetResponse().GetResponseStream()).ReadToEnd();
    var mediaLocation = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseBody)["redirect_to"];

    new WebClient().DownloadFile(mediaLocation, "D:\\test.mp4");
}
catch (Exception ex)
{
    var temp = ex.Message;
}

But every time I get an exception with this message: "The remote server returned an error: (302) FOUND."

Note that this method is called after Twilio calls my StatusCallback method which I've set when creating a new composition using CompositionResource.CreateAsync method.

Mo Sadeghipour
  • 489
  • 8
  • 25

2 Answers2

4

So, the problem was that the request was being redirected to a new location, so all I had to do was to allow redirects for the request and then download the file by copying the stream object to a file, like this:

        var uri = "https://video.twilio.com/v1/Compositions/" + sid + "/Media?Ttl=6000";

        var request = (HttpWebRequest)WebRequest.Create(uri);
        request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(_apiKeySid + ":" + _apiKeySecret)));
        request.AllowAutoRedirect = true;
        var responseBody = (await request.GetResponseAsync()).GetResponseStream();

        using (var fs = File.Create(@"D:\test.mp4"))
        {
            responseBody.CopyTo(fs);
        }
Mo Sadeghipour
  • 489
  • 8
  • 25
3

302 Found means that the resource that you are looking for has been moved to the different URL. Check the Location Header of the response to see what is the new URL.

302 Found

The HyperText Transfer Protocol (HTTP) 302 Found redirect status response code indicates that the resource requested has been temporarily moved to the URL given by the Location header. A browser redirects to this page but search engines don't update their links to the resource (in 'SEO-speak', it is said that the 'link-juice' is not sent to the new URL).

Hooman Bahreini
  • 14,480
  • 11
  • 70
  • 137