import javax.net.ssl.HttpsURLConnection;
public void sendSms() {
try {
String data = "";
data += "method=sendMessage";
data += "&userid=<userid>"; // your loginId
data += "&password=" + URLEncoder.encode("<password>", StandardCharsets.UTF_8); // your password
data += "&msg=" + URLEncoder.encode("SMS text", StandardCharsets.UTF_8);
data += "&send_to=" + URLEncoder.encode("<mobile number>", StandardCharsets.UTF_8); // a valid 10 digit phone no.
data += "&v=1.1";
data += "&msg_type=TEXT"; // Can by "FLASH" or "UNICODE_TEXT" or “BINARY”
data += "&auth_scheme=PLAIN";
URL url = new URL("https://enterprise.smsgupshup.com/GatewayAPI/rest?" + data);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.connect();
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
StringBuffer buffer = new StringBuffer();
while ((line = rd.readLine()) != null) {
buffer.append(line).append("\n");
}
System.out.println(buffer.toString());
rd.close();
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
Send Gupshup SMS using Java API
Upasana | December 23, 2019 | 3 min read | 80 views
We will use RestTemplate, OkHttpClient and Plain HttpUrlConnection to send the SMS from Gupshup provider.
We have many options when it comes to using Gupshup SMS api from Java, we will explore many of these options here in this article.
Various options that we are going to try here:
-
Using Plain Java Http Url Connection (light weight but no connection pooling)
-
Java 11 HttpClient (non-blocking and async)
-
Using RestTemplate (preferred in Spring Boot environment)
-
Using OkHttp client
Before we begin, we assume that you have valid username and password from Gupshup enterprise. And also, you should have message template approved from Gupshup.
1. Plain old Java HttpURLConnection
We can use HttpURLConnection
to establish a connection and send the GET request to remote API for SMS.
Pros and cons
-
Very light weight approach and does not require any third party library.
-
Will work on any Java version.
-
No connection pooling.
-
No auto retry, no HTTP/2 support, no compression, etc.
Java 11 HttpClient Api
Java 11 provide much enhanced version of HttpClient, which can be used to make request for sending SMS.
private void sendSms() throws IOException, InterruptedException {
HttpClient httpClient = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(10))
.build();
String data = "";
data += "method=sendMessage";
data += "&userid=<userid>"; // your loginId
data += "&password=" + URLEncoder.encode("<password>", StandardCharsets.UTF_8); // your password
data += "&msg=" + URLEncoder.encode("<SMS Text>", StandardCharsets.UTF_8);
data += "&send_to=" + URLEncoder.encode("<Mobile Number>", StandardCharsets.UTF_8); // a valid 10 digit phone no.
data += "&v=1.1";
data += "&msg_type=TEXT"; // Can by "FLASH" or "UNICODE_TEXT" or “BINARY”
data += "&auth_scheme=PLAIN";
// URL url = new URL("http://enterprise.smsgupshup.com/GatewayAPI/rest?" + data);
var request = HttpRequest.newBuilder()
.GET()
.uri(URI.create("https://enterprise.smsgupshup.com/GatewayAPI/rest?" + data))
.build();
final HttpResponse<String> httpResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(httpResponse.body());
}
Pros and cons
-
Supports HTTP/2
-
Non blocking and async method support
-
No retry and compression
-
Requires Java 11
Using RestTemplate
RestTemplate is widely used across spring boot projects for inter service communication.
private void sendSms() {
try {
RestTemplate restTemplate = new RestTemplate();
final ResponseEntity<String> responseEntity = restTemplate.exchange("https://enterprise.smsgupshup.com/GatewayAPI/rest?method=sendMessage&userid={userid}&password={password}&msg={msg}&send_to={send_to}&v={version}&msg_type={msg_type}&auth_scheme={auth_scheme}",
HttpMethod.GET, HttpEntity.EMPTY, String.class,
"<userid>", "<password>", "<SMS text>", "<mobile number>", "1.1", "TEXT", "PLAIN");
final String body = responseEntity.getBody();
System.out.println("response = " + body);
} catch (Exception e) {
e.printStackTrace();
}
}
Pros and cons
-
UriBuilder support
-
Works well with HTTP/2 and SSL
-
Connection pooling
-
Works with Java 8 onwards
Using OkHttp
OkHttp is very powerful API for making network requests and support Http/2, SSL, compression, UriBuilder etc. out of the box.
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.readTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.addInterceptor(new HttpLoggingInterceptor())
.build();
public String sendSms() throws IOException {
HttpUrl.Builder urlBuilder = HttpUrl.parse("https://enterprise.smsgupshup.com/GatewayAPI/rest").newBuilder();
urlBuilder.addQueryParameter("method", "sendMessage");
urlBuilder.addQueryParameter("userid", "<username>");
urlBuilder.addQueryParameter("password", "<password>");
urlBuilder.addQueryParameter("msg", "SMS Text");
urlBuilder.addQueryParameter("send_to", "Mobile number");
urlBuilder.addQueryParameter("v", "1.1");
urlBuilder.addQueryParameter("msg_type", "TEXT");
urlBuilder.addQueryParameter("auth_scheme", "PLAIN");
String url = urlBuilder.build().toString();
Request request = new Request.Builder().url(url).build();
logger.info("SmsGateway Sending SMS to user {}", payload);
try (Response response = okHttpClient.newCall(request).execute()) {
if (!response.isSuccessful()) {
logger.error("Error sending sms: {}", response.toString());
throw new IOException("Unexpected sms gateway code " + response.toString());
}
final String responseString = response.body().string();
logger.info("SMS gateway response {}", responseString);
return responseString;
}
}
Left over
-
Spring 5 WebClient - we will cover that in future updates
-
Declarative REST clients - feign and retrofit
Top articles in this category:
- SendGrid emails in Spring Boot
- Sendgrid Dynamic Templates with Spring Boot
- SendGrid Attachments with Spring Boot
- Basic Auth Security in Spring Boot 2
- Slack Webhook Message from Spring Boot
- Unresolved circular dependency in spring dependency injection
- Spring Boot Sidecar