Sample code for 30+ languages & platforms
Android™ Requires Chilkat v11.0.0+

Download the media files from a Twilio MMS

See more Twilio Examples

Supply the Message SID of a received or sent MMS. List its media records, then request each media resource without the .json extension to download the file bytes. Twilio may return a temporary HTTPS download URL. The example uses a separate HTTP client for that URL so the Twilio API key stays with the API host.

Run in an empty output directory. Files are written as mms-media-1.bin, mms-media-2.bin, and so on. The code prints the media SID and MIME type alongside each filename. An empty media list produces a count of zero.

Twilio documentation

Chilkat Android™ Downloads

Android™
// Important: Don't forget to include the call to System.loadLibrary
// as shown at the bottom of this code sample.
package com.test;

import android.app.Activity;
import com.chilkatsoft.*;

import android.widget.TextView;
import android.os.Bundle;

public class SimpleActivity extends Activity {

  private static final String TAG = "Chilkat";

  // Called when the activity is first created.
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    boolean success = false;

    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    //  Load an API key for the Twilio account from private application configuration.
    CkHttp http = new CkHttp();
    http.put_RequireSslCertVerify(true);
    http.put_BasicAuth(true);
    http.put_Login("YOUR_API_KEY_SID");
    http.put_Password("YOUR_API_KEY_SECRET");

    CkStringBuilder url = new CkStringBuilder();
    url.Append("https://api.twilio.com/2010-04-01/Accounts/");
    url.Append("YOUR_ACCOUNT_SID");
    url.Append("/Messages");
    url.Append("/");
    url.Append("YOUR_MESSAGE_SID");
    url.Append("/Media");
    CkStringBuilder mediaBase = new CkStringBuilder();
    mediaBase.AppendSb(url);
    url.Append(".json");
    //  Handle the API redirect explicitly so a signed download uses no Twilio credentials.
    http.put_FollowRedirects(false);
    CkHttp download = new CkHttp();
    download.put_RequireSslCertVerify(true);
    CkHttpResponse fileResp = new CkHttpResponse();
    CkStringBuilder fileUrl = new CkStringBuilder();
    CkStringBuilder filename = new CkStringBuilder();
    CkStringBuilder mediaSid = new CkStringBuilder();
    int saved = 0;
    CkHttpResponse resp = new CkHttpResponse();
    CkJsonObject reply = new CkJsonObject();

    boolean more = true;
    while ((more == true)) {
        success = http.HttpNoBody("GET",url.getAsString(),resp);
        if (resp.get_StatusCode() == 0) {
            Log.i(TAG, "No HTTP response from Twilio.");
            return;
            }

        boolean parsed = reply.Load(resp.bodyStr());
        if ((success != true) or (resp.get_StatusCode() != 200)) {
            Log.i(TAG, "Twilio returned HTTP " + String.valueOf(resp.get_StatusCode()));
            if ((parsed == true) and (reply.JsonTypeOf("code") == 2)) {
                Log.i(TAG, "Twilio error: " + String.valueOf(reply.IntOf("code")) + "  " + reply.stringOf("message"));
                }

            return;
            }

        if (parsed != true) {
            Log.i(TAG, "Expected a JSON response from Twilio.");
            return;
            }

        if (reply.JsonTypeOf("media_list") != 4) {
            Log.i(TAG, "Expected an array of media items.");
            return;
            }

        int count = reply.SizeOfArray("media_list");
        int i = 0;
        while ((i < count)) {
            reply.put_I(i);
            mediaSid.SetString(reply.stringOf("media_list[i].sid"));
            if (mediaSid.get_Length() == 0) {
                Log.i(TAG, "Media item is missing its SID.");
                return;
                }

            fileUrl.SetString(mediaBase.getAsString());
            fileUrl.Append("/");
            fileUrl.AppendSb(mediaSid);
            success = http.HttpNoBody("GET",fileUrl.getAsString(),fileResp);
            if ((fileResp.get_StatusCode() >= 300) and (fileResp.get_StatusCode() < 400)) {
                fileUrl.SetString(fileResp.getHeaderField("Location"));
                if (fileUrl.StartsWith("https://",false) != true) {
                    Log.i(TAG, "Expected an HTTPS media download URL.");
                    return;
                    }

                success = download.HttpNoBody("GET",fileUrl.getAsString(),fileResp);
                }

            if ((success != true) or (fileResp.get_StatusCode() != 200)) {
                Log.i(TAG, "Media download failed for " + mediaSid.getAsString() + ". HTTP " + String.valueOf(fileResp.get_StatusCode()));
                return;
                }

            filename.SetString("mms-media-");
            filename.AppendInt(saved + 1);
            filename.Append(".bin");
            success = fileResp.SaveBodyBinary(filename.getAsString());
            if (success == false) {
                Log.i(TAG, fileResp.lastErrorText());
                return;
                }

            Log.i(TAG, filename.getAsString() + "  " + mediaSid.getAsString() + "  " + reply.stringOf("media_list[i].content_type"));
            saved = saved + 1;
            i = i + 1;
            }

        if (reply.IsNullOf("next_page_uri") == true) {
            more = false;
            }
        else {
            url.SetString(reply.stringOf("next_page_uri"));
            if (url.StartsWith("/2010-04-01/Accounts/",true) != true) {
                Log.i(TAG, "Expected a Twilio relative next-page URI.");
                return;
                }

            url.Prepend("https://api.twilio.com");
            }

        }

    Log.i(TAG, "Media files saved: " + String.valueOf(saved));

  }

  static {
      System.loadLibrary("chilkat");

      // Note: If the incorrect library name is passed to System.loadLibrary,
      // then you will see the following error message at application startup:
      //"The application <your-application-name> has stopped unexpectedly. Please try again."
  }
}