Discussions
Java with till
almost 8 years ago by Hanan
Can use Till with Java?
almost 8 years ago by Nicholas CraffordAdmin
Yep, Till can absolutely be used with Java.
Here's an example of a send
request with standard Java i.e. no external dependencies (Java 1.7+):
Java
import java.net.URL;
import java.net.URLConnection;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.io.InputStream;
import java.io.BufferedInputStream;
public class Till {
public static String send(String endpoint, String username, String api_key, String json) throws Exception {
final URL url = new URL(endpoint + "?username=" + username + "&api_key=" + api_key);
final URLConnection conn = url.openConnection();
HttpURLConnection http = null;
try {
http = (HttpURLConnection)conn;
http.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
http.setRequestProperty("Content-Length", "" + json.getBytes().length);
http.setRequestMethod("POST");
http.setRequestProperty("User-Agent", "Mozilla/5.0");
http.setDoOutput(true);
http.setDoInput(true);
http.setUseCaches(false);
OutputStream os = null;
try {
os = http.getOutputStream();
os.write(json.getBytes("UTF-8"));
os.flush();
} finally {
if(os != null) {
os.close();
}
}
InputStream in = null;
try {
in = new BufferedInputStream(conn.getInputStream());
byte[] contents = new byte[1024];
int bytesRead = 0;
StringBuffer outStr = new StringBuffer();
while((bytesRead = in.read(contents)) != -1) {
outStr.append(new String(contents, 0, bytesRead));
}
return outStr.toString();
} finally {
if(in != null) {
in.close();
}
}
} finally {
if(http != null) {
http.disconnect();
}
}
}
public static void main(String[] args) {
try {
Till.send(
"https://platform.tillmobile.com/api/send/",
"username",
"api_key",
"{\"phone\":[\"phone_number\"], \"text\":\"Hello from Till\"}"
);
} catch(Exception e) {
System.out.println(e.toString());
}
}
}
Setup
- Save the example as
Till.java
- Replace the
username
,api_key
andphone_number
placeholders with your values - Compile via
javac Till.java
- Run via
java Till
Note: The User-Agent
header is especially important in this example. Without it the header is not sent and Till will respond with HTTP status code 403.
almost 8 years ago by Hanan
I try the above example but receive the below error [java.io.IOException: Server returned HTTP response code: 400 for URL: https://platform.tillmobile.com/api/send/?username=myUsername&api_key=myPassowrd]
almost 8 years ago by Hanan
Please ignore the above. the problem is a phone number format.
Marked as answered by Nicholas Crafford
ο»Ώ