You can use this Java Server SDK to add Vonage APIs to your application. To use this, you'll need a Vonage account. Sign up for free at vonage.com.
To use the Java Server SDK you'll need to have created a Vonage account.
To install the Java Server SDK using Gradle, add the following to build.gradle
:
repositories {
mavenCentral()
}
For Gradle 3.4 or Higher:
dependencies {
implementation 'com.vonage:client:7.3.0'
}
For older versions:
dependencies {
compile 'com.vonage:client:7.3.0'
}
Add the following to the correct place in your project's POM file:
<dependency>
<groupId>com.vonage</groupId>
<artifactId>client</artifactId>
<version>7.3.0</version>
</dependency>
Alternatively you can clone the repo and build the JAR file yourself:
git clone [email protected]:vonage/vonage-java-sdk.git
gradle build
Note: We strongly recommend that you use a tool that supports dependency management, such as Gradle, Maven, or Ivy
We provide a ZIP file for each release, containing the Java Server SDK JAR, along with all the dependencies. Download the file, unzip it, and add the JAR files to your project's classpath.
- For help understanding our APIs, check out our awesome developer portal
- Check the Javadoc for full reference documentation.
- There are also many useful code samples in our nexmo-community/nexmo-java-quickstart repository.
By default, the client will use https://api.nexmo.com, https://rest.nexmo.com, and https://sns.nexmo.com as base URIs for the various endpoints. To customize these you can instantiate VonageClient
with an HttpConfig
object.
HttpConfig.Builder
has been created to assist in building this object. Usage is as follows:
HttpConfig httpConfig = HttpConfig.builder()
.apiBaseUri("https://api.example.com")
.restBaseUri("https://rest.example.com")
.snsBaseUri("https://sns.example.com")
.build();
VonageClient client = VonageClient.builder()
.apiKey(API_KEY)
.apiSecret(API_SECRET)
.httpConfig(httpConfig)
.build();
If you do not specify a property, it will take on whatever the default value is. You can also set all three with a single method:
HttpConfig httpConfig = HttpConfig.builder().baseUri("http://example.com").build();
VonageClient client = VonageClient.builder()
.apiKey(API_KEY)
.apiSecret(API_SECRET)
.httpConfig(httpConfig)
.build();
To keep the default values, you can use HttpConfig.defaultConfig()
:
HttpConfig httpConfig = HttpConfig.defaultConfig();
VonageClient client = VonageClient.builder()
.apiKey(API_KEY)
.apiSecret(API_SECRET)
.httpConfig(httpConfig)
.build();
You can also instantiate without the parameter:
VonageClient client = VonageClient.builder()
.apiKey(API_KEY)
.apiSecret(API_SECRET)
.build();
Send an SMS with the Vonage SMS API:
VonageClient client = VonageClient.builder()
.apiKey(API_KEY)
.apiSecret(API_SECRET)
.build();
SmsSubmissionResponse responses = client.getSmsClient().submitMessage(new TextMessage(
FROM_NUMBER,
TO_NUMBER,
"Hello from Vonage!"));
for (SmsSubmissionResponseMessage response : responses.getMessages()) {
System.out.println(response);
}
Send an MMS with the Vonage Messages API:
MessageRequest request = MmsImageRequest.builder()
.from(FROM_NUMBER)
.to(TO_NUMBER)
.url(IMAGE_URL)
.caption(IMAGE_CAPTION)
.build();
MessageResponse response = client.getMessagesClient().sendMessage(request);
Send a file over Facebook Messenger using the Vonage Messages API:
MessageRequest request = MessengerFileRequest.builder()
.from(SENDER_ID)
.to(RECIPIENT_ID)
.url(FILE_URL)
.build();
MessageResponse response = client.getMessagesClient().sendMessage(request);
Send a picture over Viber using the Vonage Messages API:
MessageRequest request = ViberImageRequest.builder()
.from(SENDER_ID)
.to(TO_NUMBER)
.url(IMAGE_URL)
.build();
MessageResponse response = client.getMessagesClient().sendMessage(request);
Send a video over WhatsApp using the Vonage Messages API:
MessageRequest request = WhatsappVideoRequest.builder()
.from(FROM_NUMBER)
.to(TO_NUMBER)
.url(VIDEO_URL)
.caption(VIDEO_DESCRIPTION)
.build();
MessageResponse response = client.getMessagesClient().sendMessage(request);
The following code initiates an outbound call which then reads the user a message:
VonageClient client = VonageClient.builder()
.applicationId(APP_ID)
.privateKeyPath("application_key.pem")
.build();
Call call = new Call(to, from,
"https://nexmo-community.github.io/ncco-examples/first_call_talk.json");
CallEvent event = client.getVoiceClient().createCall(call);
After the call is answered, you can get more information about it, including the amount it cost with:
CallInfo info = client.getVoiceClient().getCallDetails(event.getUuid());
System.out.println("This cost: " + info.getPrice() + " EUR");
You can modify an existing call in progress, for example by hanging up on the current call:
ModifyCallResponse modifyResponse = client.getVoiceClient().modifyCall(event.getUuid(), ModifyCallAction.HANGUP);
System.out.println(modifyResponse.getMessage());
While a call is in progress, you can send Dual-tone multi-frequency(DTMF) tones like so:
DtmfResponse dtmfResponse = client.getVoiceClient().sendDtmf(event.getUuid(), "332393");
System.out.println("Success! " + dtmfResponse.getMessage());
To stream an audio file to an active call, simply use the following method:
StreamResponse startStreamResponse = client.getVoiceClient().startStream(event.getUuid(), "https://nexmo-community.github.io/ncco-examples/assets/voice_api_audio_streaming.mp3");
System.out.println("Success! " + startStreamResponse.getMessage());
If you'd like to stop streaming an audio file to an active call, you can do so with:
StreamResponse stopStreamResponse = client.getVoiceClient().stopStream(event.getUuid());
System.out.println("Alright. " + stopStreamResponse.getMessage());
To send a synthesized speech message to an active call, just use the following method:
TalkResponse startTalkResponse = client.getVoiceClient().startTalk(
event.getUuid(),
TalkPayload.builder("Hello, world!").language(TextToSpeechLanguage.SWEDISH).build()
);
System.out.println("Success! " + startTalkResponse.getMessage());
If you'd like to stop sending a synthesized speech message to an active call, you can do so with:
TalkResponse stopTalkResponse = client.getVoiceClient().stopTalk(event.getUuid());
System.out.println("Alright. " + stopTalkResponse.getMessage());
Our library contains a com.vonage.client.voice.ncco
package, providing JSON-serializable objects for your NCCO webhook endpoints.
Each of the Action
items contain a Builder
class that can be used for constructing various actions. These actions are then added to an Ncco
object for serialization into JSON:
TalkAction intro = TalkAction.builder("At the tone, record your response and press #.")
.build();
TalkAction outro = TalkAction.builder("Thanks, goodbye!")
.build();
RecordAction record = RecordAction.builder()
.beepStart(true)
.endOnKey('#')
.build()
res.type("application/json");
return new Ncco(intro, record, outro).toJson();
You can combine the above examples to send an NCCO to the Voice API:
The following code initiates an outbound call which then reads the user [a message](https://nexmo-community.github.io/ncco-examples/first_call_talk.json):
```java
VonageClient client = VonageClient.builder()
.applicationId(APP_ID)
.privateKeyPath("application_key.pem")
.build();
Ncco ncco = new Ncco(
TalkAction.builder("Hi, this is Russell. You are listening to a text-to-speech Call made with Vonage's Voice API")
.build()
);
Call call = new Call(to, from, ncco);
CallEvent event = client.getVoiceClient().createCall(call);
Send a 2FA code to a phone number with:
VerifyResponse ongoingVerify = client.getVerifyClient().verify(TO_NUMBER, "NEXMO");
When the user enters the code they received, you can check it like this:
client.getVerifyClient().check(ongoingVerify.getRequestId(), CODE)
Send a PSD2 code to a phone number with:
VerifyResponse verifyPayment = client.getVerifyClient().psd2Verify(TO_NUMBER, 103.33, "Michelle");
Get a list of SMS prices for a country with:
VonageClient client = VonageClient.builder()
.apiKey(API_KEY)
.apiSecret(API_SECRET)
.build();
PricingResponse response = client.getAccountClient().getSmsPrice("GB");
System.out.println(response.getDefaultPrice());
Get a list of voice prices for a country with:
PricingResponse response = client.getAccountClient().getVoicePrice("US");
System.out.println(response.getDefaultPrice());
Get a list of SMS prices for a country with:
PrefixPricingResponse response = client.getAccountClient().getPrefixPrice(ServiceType.SMS, "1");
System.out.println(response.getCountries().get(0).getDefaultPrice());
Get a list of voice prices for a country with:
PrefixPricingResponse response = client.getAccountClient().getPrefixPrice(ServiceType.VOICE, "1");
System.out.println(response.getCountries().get(0).getDefaultPrice());
Top-up your account that has auto-reload enabled with:
client.getAccountClient().topUp("TRANSACTION_NUMBER");
Submit a request to the Conversion API when it has been enabled on your account with:
client.getConversionClient().submitConversion(ConversionRequest.Type.VOICE,
"MESSAGE-ID",
true,
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2014-03-04 10:11:12"));
Create a secret associated with your account id:
SecretResponse response = client.getAccountClient().createSecret(API_KEY, "Foo84RSecret");
List the secret id (but not content) associated with your account id:
ListSecretsResponse response = client.getAccountClient().listSecrets(API_KEY);
Collection<SecretResponse> secrets = response.getSecrets();
Revoke a secret associated with your account id:
client.getAccountClient().revokeSecret(API_KEY, SECRET_ID);
Get information about a specific secret associated with your account id:
SecretResponse response = client.getAccountClient().getSecret(API_KEY, SECRET_ID);
The Vonage Video API (formerly OpenTok) is currently in beta. You can try it out by using a beta version. Usage instructions can be found on the 8.x-beta branch. See the Releases page for more information.
If you need to configure the Apache HttpClient used for making requests, you can
call VonageClient.Builder.httpClient()
to supply your custom configured object. This
can be useful, for example, if you must use an HTTP proxy to make requests or to configure SSL Certificates.
Our Voice API can connect a voice call to a websocket! An example using javax.websocket
for accepting websocket connections can be found on the Oracle website.
Another example using the Spark framework
Q: Does this SDK support thread safety? A: No, it currently does not.
Q: Does this SDK support asynchronous request / response processing? A: Currently no, but it is on the roadmap.
The following is a list of Vonage APIs and whether the Java SDK provides support for them:
API | API Release Status | Supported? |
---|---|---|
Account | General Availability | ✅ |
Alerts | General Availability | ✅ |
Application | General Availability | ✅ |
Audit | Beta | ❌ |
Conversation | Beta | ❌ |
Dispatch | Beta | ❌ |
External Accounts | Beta | ❌ |
Media | Beta | ❌ |
Messages | General Availability | ✅ |
Number Insight | General Availability | ✅ |
Number Management | General Availability | ✅ |
Pricing | General Availability | ✅ |
Redact | Developer Preview | ✅ |
Reports | Beta | ❌ |
SMS | General Availability | ✅ |
Verify | General Availability | ✅ |
Voice | General Availability | ✅ |
Video | Beta | ☑️ |
This library is released under the Apache 2.0 License
We ❤️ contributions to this library!
It is a good idea to talk to us first if you plan to add any new functionality. Otherwise, bug reports, bug fixes and feedback on the library are always appreciated.