- Notifications
You must be signed in to change notification settings - Fork445
A Java library for communicating with the Twilio REST API and generating TwiML.
License
twilio/twilio-java
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
The documentation for the Twilio API can be foundhere.
The Java library documentation can be foundhere.
twilio-java
uses a modified version ofSemantic Versioning for all changes.See this document for details.
New accounts and subaccounts are now required to use TLS 1.2 when accessing the REST API."Upgrade Required" errors indicate that TLS 1.0/1.1 is being used.
This library supports the following Java implementations:
- OpenJDK 8
- OpenJDK 11
- OpenJDK 17
- OracleJDK 8
- OracleJDK 11
- OracleJDK 17
For Java 7 support, usetwilio-java
major version7.X.X
.
To indicate that a class or method is in beta and subject to change, we use the@Beta
annotation. For example:
@BetapublicclassClassName {// Class implementation}publicclassClassName {@Betapublicvoidinit() {// Implementation }}
twilio-java
uses Maven. At present the jarsare available from a publicmaven repository.
Use the following dependency in your project to grab via Maven:
<dependency> <groupId>com.twilio.sdk</groupId> <artifactId>twilio</artifactId> <version>10.X.X</version> <scope>compile</scope></dependency>
or Gradle:
implementation"com.twilio.sdk:twilio:10.X.X"
If you want to compile it yourself, here's how:
git clone git@github.com:twilio/twilio-javacd twilio-javamvn install# Requires maven, download from https://maven.apache.org/download.html
If you want to build your own .jar, execute the following from within the cloned directory:
mvn package
If you run into trouble with local tests, use:
mvn package -Dmaven.test.skip=true
Try sending yourself an SMS message, like this:
importcom.twilio.Twilio;importcom.twilio.rest.api.v2010.account.Message;importcom.twilio.type.PhoneNumber;publicclassExample {// Find your Account Sid and Token at console.twilio.compublicstaticfinalStringACCOUNT_SID ="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";publicstaticfinalStringAUTH_TOKEN ="your_auth_token";publicstaticvoidmain(String[]args) {Twilio.init(ACCOUNT_SID,AUTH_TOKEN);Messagemessage =Message .creator(newPhoneNumber("+15558675309"),newPhoneNumber("+15017250604"),"This is the ship that made the Kessel Run in fourteen parsecs?" ) .create();System.out.println(message.getSid()); }}
WarningIt's okay to hardcode your credentials when testing locally, but you should use environment variables to keep them secret before committing any code or deploying to production. Check outHow to Set Environment Variables for more information.
importcom.twilio.Twilio;importcom.twilio.exception.AuthenticationException;publicclassExample {privatestaticfinalStringACCOUNT_SID ="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";privatestaticfinalStringAUTH_TOKEN ="your_auth_token";publicstaticvoidmain(String[]args)throwsAuthenticationException {Twilio.init(ACCOUNT_SID,AUTH_TOKEN); }}
The above example shows how to initialize the client in case the endpoints use basic authentication. When the endpoint does not require any authentication, use TwilioNoAuth client instead.There are endpoints like Organization domain which uses bearer token authentication. Custom Clients needs to be used in such cases and initialize them with the values required for access token generation.
To bypass the initialization step you can also use a custom token manager implementation. Token manager class should implement the Token interface and call a token generation endpoint of your choice.Detailed exampleshere
twilio-java
supports the credentials, region, and edge values stored in the following environment variables:
TWILIO_ACCOUNT_SID
TWILIO_AUTH_TOKEN
TWILIO_REGION
TWILIO_EDGE
If using these variables, the above client initialization can be skipped.
importcom.twilio.Twilio;importcom.twilio.rest.api.v2010.account.Call;importcom.twilio.type.PhoneNumber;importjava.net.URI;importjava.net.URISyntaxException;publicclassExample {publicstaticfinalStringACCOUNT_SID ="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";publicstaticfinalStringAUTH_TOKEN ="your_auth_token";publicstaticvoidmain(String[]args)throwsURISyntaxException {Twilio.init(ACCOUNT_SID,AUTH_TOKEN);Callcall =Call .creator(newPhoneNumber("+14155551212"),newPhoneNumber("+15017250604"),newURI("http://demo.twilio.com/docs/voice.xml") ) .create();System.out.println(call.getSid()); }}
importcom.twilio.Twilio;importcom.twilio.rest.api.v2010.account.Call;publicclassExample {publicstaticfinalStringACCOUNT_SID ="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";publicstaticfinalStringAUTH_TOKEN ="your_auth_token";publicstaticvoidmain(String[]args) {Twilio.init(ACCOUNT_SID,AUTH_TOKEN);Callcall =Call.fetcher("CA42ed11f93dc08b952027ffbc406d0868").fetch();System.out.println(call.getTo()); }}
We are introducing Client Credentials Flow-based OAuth 2.0 authentication.This feature is currently inbeta
and its implementation is subject to change.
The library automatically handles paging for you. With theread
method, you can specify the number of records you want to receive (limit
) and the maximum size you want each page fetch to be (pageSize
). The library will then handle the task for you, fetching new pages under the hood as you iterate over the records.
For more information, view theauto-generated library docs.
importcom.twilio.Twilio;importcom.twilio.base.ResourceSet;importcom.twilio.rest.api.v2010.account.Call;publicclassExample {publicstaticfinalStringACCOUNT_SID ="ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";publicstaticfinalStringAUTH_TOKEN ="your_auth_token";publicstaticvoidmain(String[]args) {Twilio.init(ACCOUNT_SID,AUTH_TOKEN);ResourceSet<Call>calls =Call.reader().read();for (Callcall :calls) {System.out.println(call.getDirection()); } }}
To take advantage of Twilio'sGlobal Infrastructure, specify the target Region and/or Edge for the client:
Twilio.init(accountSid,authToken);Twilio.setRegion("au1");Twilio.setEdge("sydney");
This will result in thehostname
transforming fromapi.twilio.com
toapi.sydney.au1.twilio.com
.
To use multiple region within same application, referMultiRegionClient.md
This library uses SLF4J for logging. Consult theSFL4J documentation for information about logging configuration.
For example, if you are usinglog4j
:
Make sure you have
log4j-slf4j-impl
,log4j-core
andlog4j-api
in yourpom.xml
fileDefine the logging level for the Twilio HTTP client in your configuration. For example, in
src/main/resources/log4j2.xml
:<?xml version="1.0" encoding="UTF-8"?><Configurationstatus="WARN"> <Appenders> <Consolename="Console"target="SYSTEM_OUT"> <PatternLayoutpattern="%d{HH:mm:ss.SSS} %-5level - %msg%n"/> </Console> </Appenders> <Loggers><!--Your Twilio logging configuration goes here--> <Loggername="com.twilio.http"level="debug"additivity="false"> <AppenderRefref="Console"/> </Logger> <Rootlevel="info"> <AppenderRefref="Console"/> </Root> </Loggers></Configuration>
importcom.twilio.exception.ApiException;try {Messagemessage =Message.creator(newPhoneNumber("+15558881234"),// To numbernewPhoneNumber("+15559994321"),// From number"Hello world!"// SMS body ).create();System.out.println(message.getSid());}catch (finalApiExceptione) {System.err.println(e);}
Additional documentation here:https://twilio.com/docs/iam/pkcv/quickstart
ValidationClienthttpClient =newValidationClient(ACCOUNT_SID,key.getSid(),signingKey.getSid(),pair.getPrivate());TwilioRestClientclient =newTwilioRestClient.Builder(signingKey.getSid(),signingKey.getSecret()) .accountSid(ACCOUNT_SID) .httpClient(httpClient) .build();
To control phone calls, your application needs to outputTwiML.
TwiML in twilio-java now use the builder pattern!
TwiMLtwiml =newVoiceResponse.Builder() .say(newSay.Builder("Hello World!").build()) .play(newPlay.Builder("https://api.twilio.com/cowbell.mp3").loop(5).build()) .build();
That will output XML that looks like this:
<Response> <Say>Hello World!</Say> <Playloop="5">https://api.twilio.com/cowbell.mp3</Play></Response>
To use a custom HTTP client with this helper library, please see theadvanced example of how to do so.
TheDockerfile
present in this repository and its respectivetwilio/twilio-java
Docker image are currently used by Twilio for testing purposes only.
If you need help installing or using the library, please check theTwilio Support Help Center first, andfile a support ticket if you don't find an answer to your question.
If you've instead found a bug in the library or would like new features added, go ahead and open issues or pull requests against this repo!
About
A Java library for communicating with the Twilio REST API and generating TwiML.
Topics
Resources
License
Code of conduct
Uh oh!
There was an error while loading.Please reload this page.