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:

  1. Using Plain Java Http Url Connection (light weight but no connection pooling)

  2. Java 11 HttpClient (non-blocking and async)

  3. Using RestTemplate (preferred in Spring Boot environment)

  4. 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.

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();
}
}

Pros and cons

  1. Very light weight approach and does not require any third party library.

  2. Will work on any Java version.

  3. No connection pooling.

  4. 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.

Java 11 HttpClient
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

  1. Supports HTTP/2

  2. Non blocking and async method support

  3. No retry and compression

  4. 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

  1. UriBuilder support

  2. Works well with HTTP/2 and SSL

  3. Connection pooling

  4. 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.

OkHttp for sending SMS
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

  1. Spring 5 WebClient - we will cover that in future updates

  2. Declarative REST clients - feign and retrofit


Top articles in this category:
  1. SendGrid emails in Spring Boot
  2. Sendgrid Dynamic Templates with Spring Boot
  3. SendGrid Attachments with Spring Boot
  4. Basic Auth Security in Spring Boot 2
  5. Slack Webhook Message from Spring Boot
  6. Unresolved circular dependency in spring dependency injection
  7. Spring Boot Sidecar

Recommended books for interview preparation:

Find more on this topic:
Buy interview books

Java & Microservices interview refresher for experienced developers.