I came across a question on StackOverflow.com yesterday. As, I have used Twilio API to send SMS and do Phone Call many times. I signed up to help the OP.
If you wanna compile following code in your local box, then you need to have JSON.jar and commons-codec-1.8.jar JAR files. Download File Archive
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
package com.gaurangjadia.code.controllers; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.codec.binary.Base64; import org.json.*; import com.gaurangjadia.code.base.WebFramework; import com.gaurangjadia.code.base.WebFramework.HttpMethod; @WebServlet("/Twilio") public class Twilio extends HttpServlet { private static final long serialVersionUID = 1L; public Twilio() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.getRequestDispatcher("/WEB-INF/twilio.jsp?strResponse=").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String strToNumber = request.getParameter("toNumber"); String strBody = request.getParameter("body"); WebFramework objWebFramework = new WebFramework(); Map<String, String> mapParameters = new HashMap<String, String>(); mapParameters.put("From", "+16264869550"); mapParameters.put("To", strToNumber); mapParameters.put("Body", strBody); String authString = "AC2ce688407e7089dfd0f93eec57db9620:2b84176caf367d6ab02959c175d89599"; byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); String authStringEnc = new String(authEncBytes); Map<String, String> mapHeaders = new HashMap<String, String>(); mapHeaders.put("Authorization", "Basic " + authStringEnc); String strResponse = objWebFramework.doHttpRequest("https://api.twilio.com/2010-04-01/Accounts/AC2ce688407e7089dfd0f93eec57db9620/SMS/Messages.json", HttpMethod.POST, mapParameters, mapHeaders); //To Pretty Print JSON Response JSONObject objJSON = new JSONObject(strResponse); request.getRequestDispatcher("/WEB-INF/twilio.jsp?strResponse=" + objJSON.toString(3)).forward(request, response); } } |
I wrote this class to generalize any Web Related Helper Methods.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 |
package com.gaurangjadia.code.base; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.Map; public class WebFramework { public enum HttpMethod { GET, POST, HEAD, DELETE, PUT } /** * Return String Response after calling given URL * * @param strURL URL to make request * @param httpMethod HTTP Method to Call (GET, POST, HEAD, DELETE, PUT) * @param mapParameters Collection of Arguments to pass in the HTTP WebRequest * @param mapHeaders Collection of Arguments to pass in the HTTP Headers * @return String Response came from remote server * @throws IOException */ public String doHttpRequest(String strURL, HttpMethod httpMethod, Map<String, String> mapParameters, Map<String, String> mapHeaders) throws IOException{ String strResponse = ""; if (httpMethod == WebFramework.HttpMethod.GET) { URL objURL = new URL(strURL + "?" + this.encodeMap(mapParameters)); HttpURLConnection objConnection = (HttpURLConnection) objURL.openConnection(); objConnection.setRequestMethod("GET"); BufferedReader in = new BufferedReader(new InputStreamReader(objConnection.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); strResponse = response.toString(); } else if (httpMethod == WebFramework.HttpMethod.POST) { URL objURL = new URL(strURL); HttpURLConnection objConnection = (HttpURLConnection) objURL.openConnection(); objConnection.setRequestMethod("POST"); for (Map.Entry<String, String> entry : mapHeaders.entrySet()) { objConnection.setRequestProperty(entry.getKey().toString(), entry.getValue().toString()); } objConnection.setDoOutput(true); DataOutputStream wr = new DataOutputStream(objConnection.getOutputStream()); wr.writeBytes(this.encodeMap(mapParameters)); wr.flush(); wr.close(); BufferedReader in = new BufferedReader(new InputStreamReader(objConnection.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); strResponse = response.toString(); } else { throw new UnsupportedOperationException("HEAD, DELETE and PUT methods yet not supported"); } return strResponse; } public String encodeMap(Map<String, String> map) throws UnsupportedEncodingException { StringBuilder sb = new StringBuilder(); for (Map.Entry<String, String> entry : map.entrySet()) { if (sb.length() > 0) { sb.append("&"); } sb.append(String.format("%s=%s", urlEncodeUTF8(entry.getKey().toString()), urlEncodeUTF8(entry.getValue().toString()) )); } return sb.toString(); } static String urlEncodeUTF8(String s) throws UnsupportedEncodingException { return URLEncoder.encode(s, "UTF-8"); } } |
To output property, I used Bootstrap 2.3.2 in following JSP.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
<%@ page language="java" contentType="text/html; charset=US-ASCII" pageEncoding="US-ASCII"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE html> <html> <head> <title>Twilio Messages (Send message Example)</title> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="http://getbootstrap.com/2.3.2/assets/css/bootstrap.css" rel="stylesheet"> <link href="http://getbootstrap.com/2.3.2/assets/css/bootstrap-responsive.css" rel="stylesheet"> </head> <body> <div class="container"> <div class="row"> <div class="span12"> <h2>Twilio Messages (Send message Example)</h2> <form class="form-signin" action="Twilio" method="post"> <div class="row"> <div class="span3"> Enter Number to send: </div> <div class="span3"> <input type="text" name="toNumber" maxlength="10" placeholder="Enter 10 digits number to send" value="+16822037149"/> </div> <div class="span6"> <div class="alert"> <button type="button" class="close" data-dismiss="alert">×</button> The number to send an SMS to. This field accepts formatted and unformatted US numbers, e.g. +14155551212, (415) 555-1212 or 415-555-1212.<hr /> To send message from SandBox Account. The Number has to be <a href="https://www.twilio.com/user/account/phone-numbers/verified" target="_blank">verified</a> </div> </div> </div> <div class="row"> <div class="span3"> Enter Message to send: </div> <div class="span3"> <textarea name="body" maxlength="160" placeholder="Enter message to send"> </textarea> </div> <div class="span6"> <div class="alert"> <button type="button" class="close" data-dismiss="alert">×</button> The text of the message you want to send, limited to 160 characters. </div> </div> </div> <div class="row"> <div class="span3"> </div> <div class="span9"> <button class="btn" type="submit">Send</button> </div> </div> </form> </div> </div> <c:if test="${param.strResponse != ''}"> <div class="row"> <div class="span12"> <div class="alert alert-success"> Well Done! Message is send!!! </div> <textarea style="width: 100%; height: 350px; font-family: monospace; font-weight: 900;" readonly="readonly"> <c:out value="${param.strResponse}"></c:out> </textarea> </div> </div> </c:if> </div> </body> <script type="text/javascript" src="https://code.jquery.com/jquery.min.js"></script> <script type="text/javascript" src="http://getbootstrap.com/2.3.2/assets/js/bootstrap.js"></script> </html> |
If you get all things working, the output would look like this.