Sample code for 30+ languages & platforms
Java 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 Java Downloads

Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Http;
import com.chilkatsoft.chilkat2.HttpResponse;
import com.chilkatsoft.chilkat2.JsonObject;
import com.chilkatsoft.chilkat2.StringBuilder;

public class ChilkatExample {

    public static void main(String[] args) {
        boolean success = false;

        // Assumes Chilkat is unlocked. See Global Unlock Sample.
        // Load an API key for the Twilio account from private application configuration.
        Http http = new Http();
        http.setRequireSslCertVerify(true);
        http.setBasicAuth(true);
        http.setLogin("YOUR_API_KEY_SID");
        http.setPassword("YOUR_API_KEY_SECRET");

        StringBuilder url = new StringBuilder();
        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");
        StringBuilder mediaBase = new StringBuilder();
        mediaBase.appendSb(url);
        url.append(".json");
        // Handle the API redirect explicitly so a signed download uses no Twilio credentials.
        http.setFollowRedirects(false);
        Http download = new Http();
        download.setRequireSslCertVerify(true);
        HttpResponse fileResp = new HttpResponse();
        StringBuilder fileUrl = new StringBuilder();
        StringBuilder filename = new StringBuilder();
        StringBuilder mediaSid = new StringBuilder();
        int saved = 0;
        HttpResponse resp = new HttpResponse();
        JsonObject reply = new JsonObject();

        boolean more = true;
        while (more) {
            try {
                http.httpNoBody("GET", url.getAsString(), resp);
                success = true;
            } catch (ChilkatException e) {
                success = false;
            }
            if (resp.getStatusCode() == 0) {
                System.out.println("No HTTP response from Twilio.");
                return;
            }

            boolean parsed;
            try {
                reply.load(resp.getBodyStr());
                parsed = true;
            } catch (ChilkatException e) {
                parsed = false;
            }
            if ((!success) || (resp.getStatusCode() != 200)) {
                System.out.println("Twilio returned HTTP " + resp.getStatusCode());
                if ((parsed) && (reply.jsonTypeOf("code") == 2)) {
                    System.out.println("Twilio error: " + reply.intOf("code") + "  " + reply.stringOf("message"));
                }

                return;
            }

            if (!parsed) {
                System.out.println("Expected a JSON response from Twilio.");
                return;
            }

            if (reply.jsonTypeOf("media_list") != 4) {
                System.out.println("Expected an array of media items.");
                return;
            }

            int count = reply.sizeOfArray("media_list");
            int i = 0;
            while (i < count) {
                reply.setI(i);
                mediaSid.setString(reply.stringOf("media_list[i].sid"));
                if (mediaSid.getLength() == 0) {
                    System.out.println("Media item is missing its SID.");
                    return;
                }

                fileUrl.setString(mediaBase.getAsString());
                fileUrl.append("/");
                fileUrl.appendSb(mediaSid);
                http.httpNoBody("GET", fileUrl.getAsString(), fileResp);
                if ((fileResp.getStatusCode() >= 300) && (fileResp.getStatusCode() < 400)) {
                    fileUrl.setString(fileResp.getHeaderField("Location"));
                    if (!fileUrl.startsWith("https://", false)) {
                        System.out.println("Expected an HTTPS media download URL.");
                        return;
                    }

                    try {
                        download.httpNoBody("GET", fileUrl.getAsString(), fileResp);
                        success = true;
                    } catch (ChilkatException e) {
                        success = false;
                    }
                }

                if ((!success) || (fileResp.getStatusCode() != 200)) {
                    System.out.println("Media download failed for " + mediaSid.getAsString() + ". HTTP " + fileResp.getStatusCode());
                    return;
                }

                filename.setString("mms-media-");
                filename.appendInt(saved + 1);
                filename.append(".bin");
                try {
                    fileResp.saveBodyBinary(filename.getAsString());
                } catch (ChilkatException e) {
                    System.out.println(e.getLastErrorText());
                    return;
                }

                System.out.println(filename.getAsString() + "  " + mediaSid.getAsString() + "  " + reply.stringOf("media_list[i].content_type"));
                saved = saved + 1;
                i = i + 1;
            }

            if (reply.isNullOf("next_page_uri")) {
                more = false;
            } else {
                url.setString(reply.stringOf("next_page_uri"));
                if (!url.startsWith("/2010-04-01/Accounts/", true)) {
                    System.out.println("Expected a Twilio relative next-page URI.");
                    return;
                }

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

        System.out.println("Media files saved: " + saved);
    }
}