This repository was archived by the owner on Nov 13, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathClickatellHttp.java
More file actions
509 lines (476 loc) · 15.7 KB
/
ClickatellHttp.java
File metadata and controls
509 lines (476 loc) · 15.7 KB
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
/**
* This is an example of how to use the Clickatell HTTP API. NOTE: this is not
* the only way, this is just an example. This class can also be used as a
* library if you wish.
*
* @date Dec 2, 2014
* @author Dominic Schaff <dominic.schaff@gmail.com>
*/
public class ClickatellHttp {
/**
* @var The URL to use for the base of the HTTP API.
*/
private static final String CLICKATELL_HTTP_BASE_URL = "https://api.clickatell.com/http/";
/**
* @var The URL to use for the base of the HTTP/UTILS API.
*/
private static final String CLICKATELL_UTILS_BASE_URL = "https://api.clickatell.com/utils/";
/**
* @var The three private variables to use for authentication.
*/
private String userName, apiId, password;
/**
* Create a HTTP object, and set the auth, but not test the auth.
*/
public ClickatellHttp(String userName, String apiId, String password) {
this.userName = userName;
this.apiId = apiId;
this.password = password;
}
/**
* This tests whether your account details works.
*
* @return True if details were accepted, and false otherwise.
* @throws UnknownHostException
*/
public boolean testAuth() throws UnknownHostException {
try {
// Build Parameters:
String urlParameters = "user="
+ URLEncoder.encode(this.userName, "UTF-8") + "&api_id="
+ URLEncoder.encode(this.apiId, "UTF-8") + "&password="
+ URLEncoder.encode(this.password, "UTF-8");
// Send Request:
String result = this.excutePost(CLICKATELL_HTTP_BASE_URL
+ "auth.php", urlParameters);
// Check whether an auth failed happened:
return result.startsWith("OK: ");
} catch (UnsupportedEncodingException e) {
}
return false;
}
/**
* This will attempt to get your current balance.
*
* @throws Exception
* This will be thrown if your auth details were incorrect.
*
* @return Your balance.
*/
public double getBalance() throws Exception {
// Build Parameters:
String urlParameters = "user="
+ URLEncoder.encode(this.userName, "UTF-8") + "&api_id="
+ URLEncoder.encode(this.apiId, "UTF-8") + "&password="
+ URLEncoder.encode(this.password, "UTF-8");
// Send Request:
String result = this.excutePost(CLICKATELL_HTTP_BASE_URL
+ "getbalance.php", urlParameters);
// Check whether an auth failed happened:
if (result.contains("Authentication failed")) {
throw new Exception("Authentication Failed");
}
if (result.startsWith("ERR")) {
throw new Exception(result);
}
// We know the balance is the second part of the query:
String[] a = result.split(" ");
return Double.parseDouble(a[1]);
}
/**
* This sends a single message.
*
* @param number
* The number that you wish to send to. This should be in
* international format.
* @param messageContent
* The message you want to send,
*
* @throws Exception
* This gets thrown on an auth failure.
* @return A Message object that contains the resulting information.
*/
public Message sendMessage(String number, String messageContent)
throws Exception {
// Build Parameters:
String urlParameters = "user="
+ URLEncoder.encode(this.userName, "UTF-8") + "&api_id="
+ URLEncoder.encode(this.apiId, "UTF-8") + "&password="
+ URLEncoder.encode(this.password, "UTF-8") + "&to="
+ URLEncoder.encode(number, "UTF-8") + "&text="
+ URLEncoder.encode(messageContent, "UTF-8");
// Send Request:
String result = this.excutePost(CLICKATELL_HTTP_BASE_URL
+ "sendmsg.php", urlParameters);
// Check whether an auth failed happened:
if (result.contains("Authentication failed")) {
throw new Exception("Authentication Failed");
}
String a[] = result.split(": ");
Message message = new Message();
message.number = number;
message.content = messageContent;
// Check whether there is no credit left in the account:
if (result.toLowerCase().startsWith("err")) {
message.error = a[1];
return message;
}
message.message_id = a[1].trim();
return message;
}
/**
* This is to send the same message to multiple people. Only use this
* function to send a maximum of 300 messages, and a minimum of 2.
*
* @param numbers
* The array of numbers that are to be sent to.
* @param messageContent
* The message that you would like to send.
*
* @return The returned array contains the messages sent with their
* resulting information.
*
* @throws Exception
* This gets thrown on auth errors.
*/
public Message[] sendMessage(String[] numbers, String messageContent)
throws Exception {
if (numbers.length < 2 || numbers.length > 300) {
throw new Exception("Illegal arguments passed");
}
ArrayList<Message> messages = new ArrayList<Message>();
// Build Parameters:
String urlParameters = "user="
+ URLEncoder.encode(this.userName, "UTF-8") + "&api_id="
+ URLEncoder.encode(this.apiId, "UTF-8") + "&password="
+ URLEncoder.encode(this.password, "UTF-8") + "&text="
+ URLEncoder.encode(messageContent, "UTF-8") + "&to=";
urlParameters += numbers[0];
for (int x = 1; x < numbers.length; x++) {
urlParameters += "," + numbers[x];
}
// Send Request:
String result = this.excutePost(CLICKATELL_HTTP_BASE_URL
+ "sendmsg.php", urlParameters);
// Check whether an auth failed happened:
if (result.contains("Authentication failed")) {
throw new Exception("Authentication Failed");
}
// We don't throw an exception here, as maybe only part of your
// messages failed:
String lines[] = result.split("\n");
for (String l : lines) {
String n[] = l.split(" To: ");
Message message = new Message();
message.number = n[1].trim();
String q[] = n[0].split(": ");
if (q[0].equalsIgnoreCase("err")) {
message.error = q[1];
} else {
message.message_id = q[1];
}
messages.add(message);
}
return messages.toArray(new Message[0]);
}
/**
* This will attempt to get the message status of a single message.
*
* @param messageId
* This is the message ID that you received when sending the
* message.
*
* @return The status of the message.
*
* @throws Exception
* if there is an error with the request.
*/
public int getMessageStatus(String messageId) throws Exception {
String urlParameters;
// Build Parameters:
urlParameters = "user=" + URLEncoder.encode(this.userName, "UTF-8")
+ "&api_id=" + URLEncoder.encode(this.apiId, "UTF-8")
+ "&password=" + URLEncoder.encode(this.password, "UTF-8")
+ "&apimsgid=" + URLEncoder.encode(messageId, "UTF-8");
// Send Request:
String result = this.excutePost(CLICKATELL_HTTP_BASE_URL
+ "querymsg.php", urlParameters);
// Check whether an auth failed happened:
if (result.contains("Authentication failed")) {
throw new Exception("Authentication Failed");
}
// If there was an error, throw it.
if (result.startsWith("ERR:")) {
throw new Exception(result);
}
// We know the status will always be the fourth part:
// Syntax: ID: xxx Status: xxx
String[] a = result.split(" ");
return Integer.parseInt(a[3].trim());
}
/**
* This will get the status and charge of the message given by the
* messageId.
*
* @param messageId
* The message ID that should be searched for.
*
* @return A Message object with the requested data will be returned.
*
* @throws Exception
* If there was an error with the request.
*/
public Message getMessageCharge(String messageId) throws Exception {
String urlParameters;
// Build Parameters:
urlParameters = "user=" + URLEncoder.encode(this.userName, "UTF-8")
+ "&api_id=" + URLEncoder.encode(this.apiId, "UTF-8")
+ "&password=" + URLEncoder.encode(this.password, "UTF-8")
+ "&apimsgid=" + URLEncoder.encode(messageId, "UTF-8");
// Send Request:
String result = this.excutePost(CLICKATELL_HTTP_BASE_URL
+ "getmsgcharge.php", urlParameters);
// Check whether an auth failed happened:
if (result.contains("Authentication failed")) {
throw new Exception("Authentication Failed");
}
Message message = new Message(messageId);
// If there was an error, throw it.
if (result.startsWith("ERR:")) {
message.error = result.substring(4);
} else {
String[] a = result.split(" ");
message.status = a[5].trim();
message.charge = a[3].trim();
}
return message;
}
/**
* This will try to stop a message that has been sent. Note that only
* messages that are going to be sent in the future can be stopped. Or if by
* some luck you message has not been sent to the operator yet.
*
* @param messageId
* The message ID that is to be stopped.
*
* @return The status after requesting the message to be stopped.
*
* @throws Exception
* If there was something wrong with the request.
*/
public int stopMessage(String messageId) throws Exception {
String urlParameters;
// Build Parameters:
urlParameters = "user=" + URLEncoder.encode(this.userName, "UTF-8")
+ "&api_id=" + URLEncoder.encode(this.apiId, "UTF-8")
+ "&password=" + URLEncoder.encode(this.password, "UTF-8")
+ "&apimsgid=" + URLEncoder.encode(messageId, "UTF-8");
// Send Request:
String result = this.excutePost(
CLICKATELL_HTTP_BASE_URL + "delmsg.php", urlParameters);
// Check whether an auth failed happened:
if (result.contains("Authentication failed")) {
throw new Exception("Authentication Failed");
}
// If there was an error, throw it.
if (result.startsWith("ERR")) {
throw new Exception(result);
}
// Split the result we know that the status will always the fourth
// part:
// Format: ID: xxx Status: xxx
String[] a = result.split(" ");
return Integer.parseInt(a[3].trim());
}
/**
* This attempts to get coverage data for the given number. A -1 means no
* coverage, all else is the minimum cost the message could charge.
*
* @param number
* The number the lookup should be done on.
* @return The minimum possible cost, or a -1 on error.
* @throws Exception
* If there was something wrong with the request.
*/
public double getCoverage(String number) throws Exception {
// Build Parameters:
String urlParameters = "user="
+ URLEncoder.encode(this.userName, "UTF-8") + "&api_id="
+ URLEncoder.encode(this.apiId, "UTF-8") + "&password="
+ URLEncoder.encode(this.password, "UTF-8") + "&msisdn="
+ URLEncoder.encode(number, "UTF-8");
// Send Request:
String result = this.excutePost(CLICKATELL_UTILS_BASE_URL
+ "routecoverage.php", urlParameters);
// Check whether an auth failed happened:
if (result.contains("Authentication failed")) {
throw new Exception("Authentication Failed");
}
if (result.startsWith("ERR")) {
return -1;
}
String[] a = result.split("Charge: ");
return Double.parseDouble(a[1]);
}
/**
* This will allow you to use any feature of the API. Note that you can do
* more powerful things with this function. And as such should only be used
* once you have read the documentation, as the parameters are passed
* directly to the API.
*
* @param numbers
* The list of numbers that must be sent to.
* @param messageContent
* The message that is to be sent.
* @param features
* The extra features that should be included.
*
* @return An array of Messages which will contain the data for each message
* sent.
*
* @throws Exception
* If there is anything wrong with the submission this will get
* thrown.
*/
public Message[] sendAdvancedMessage(String[] numbers,
String messageContent, HashMap<String, String> features)
throws Exception {
ArrayList<Message> messages = new ArrayList<Message>();
String urlParameters;
// Build Parameters:
urlParameters = "user=" + URLEncoder.encode(this.userName, "UTF-8")
+ "&api_id=" + URLEncoder.encode(this.apiId, "UTF-8")
+ "&password=" + URLEncoder.encode(this.password, "UTF-8")
+ "&text=" + URLEncoder.encode(messageContent, "UTF-8");
String number = numbers[0];
for (int x = 1; x < numbers.length; x++) {
number += "," + numbers[x];
}
urlParameters += "&to=" + number;
for (Entry<String, String> entry : features.entrySet()) {
urlParameters += "&" + entry.getKey() + "="
+ URLEncoder.encode(entry.getValue(), "UTF-8");
}
// Send Request:
String result = this.excutePost(CLICKATELL_HTTP_BASE_URL
+ "sendmsg.php", urlParameters);
// Check whether an auth failed happened:
if (result.contains("Authentication failed")) {
throw new Exception("Authentication Failed");
}
// This does some fancy swapping:
String lines[] = result.split("\n");
if (lines.length > 1) { // Sent more than one message
for (String l : lines) {
Message message = new Message();
String i[] = l.split(" To: ");
message.number = i[1];
String n[] = i[0].split(": ");
if (n[0].equalsIgnoreCase("err")) {
message.error = n[1];
} else {
message.message_id = n[1];
}
}
} else { // Sent one message
String n[] = lines[0].split(": ");
Message message = new Message();
message.number = numbers[0];
if (n[0].equalsIgnoreCase("err")) {
message.error = n[1];
} else {
message.message_id = n[1];
}
}
return messages.toArray(new Message[0]);
}
/**
* This executes a POST query with the given parameters.
*
* @param targetURL
* The URL that should get hit.
* @param urlParameters
* The data you want to send via the POST.
*
* @return The content of the request.
* @throws UnknownHostException
*/
private String excutePost(String targetURL, String urlParameters)
throws UnknownHostException {
URL url;
HttpURLConnection connection = null;
try {
// Create connection
url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length",
"" + Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
// Send request
DataOutputStream wr = new DataOutputStream(
connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
// Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\n');
}
rd.close();
return response.toString();
} catch (UnknownHostException e) {
throw e;
} catch (Exception e) {
return "";
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
/**
* This is the Message class that gets used as return values for some of the
* functions.
*
* @author Dominic Schaff <dominic.schaff@gmail.com>
*
*/
public class Message {
public String number = null, message_id = null, content = null,
charge = null, status = null, error = null;
public Message(String message_id) {
this.message_id = message_id;
}
public Message() {
}
public String toString() {
if (message_id != null) {
return number + ": " + message_id;
}
return number + ": " + error;
}
}
}