MyAuthenticator.java
import java.net.Authenticator; import java.net.PasswordAuthentication; /** * MyAuthenticator is the class to authenticate the user using userName and password * @author Harit Kumar */ public class MyAuthenticator extends Authenticator{ private String user; private String passwd; public MyAuthenticator(String user, String passwd) { this.user = user; this.passwd = passwd; } public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(user, passwd.toCharArray()); } }PushUtil.java
import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.net.Authenticator; import java.net.URL; import java.net.URLConnection; import javax.net.ssl.HttpsURLConnection; import org.apache.log4j.Logger; public class PushUtil { static Logger logger = Logger.getLogger(PushUtil.class); public static boolean sendPushMessage(String message,String deviceToken){ boolean result=false; try { Authenticator.setDefault(new MyAuthenticator("App Key","App Master Secret")); URL url = new URL("https://go.urbanairship.com/api/push/"); URLConnection urlConnection = url.openConnection(); HttpsURLConnection httpConn = (HttpsURLConnection)urlConnection; ByteArrayOutputStream bout = new ByteArrayOutputStream(); String postdata = "{\"aps\": {\"alert\": \""+message+"\"}, \"device_tokens\": [\""+deviceToken+"\"]}"; logger.info("postdata : "+postdata); byte[] buffer = new byte[postdata.length()]; buffer = postdata.getBytes("UTF8"); bout.write(buffer); byte[] b = bout.toByteArray(); httpConn.setRequestProperty("Content-Length",String.valueOf(b.length)); httpConn.setRequestProperty("Content-Type","application/json"); httpConn.setRequestMethod("POST"); httpConn.setDoOutput(true); httpConn.setDoInput(true); OutputStream out = httpConn.getOutputStream(); out.write(b); out.close(); logger.info("Push ResponseCode : "+httpConn.getResponseCode()); if(httpConn.getResponseCode()==200) { result=true; } } catch (Exception e) { logger.error("Error : "+e); } return result; } public static void main(String[] args) { PushUtil.sendPushMessage("Hi Demo","98b79b2f 74f4457d 55966598 03be5fa3 36693326 37700848 33454309 c408f253"); } }
This is a great tutorial.
ReplyDeleteI was trying another payload but it received a 400 response even though it is tested valid JSON.
{"audience": {"alias": "some_alias"}, "notification": {"alert": "Hi demo from Java application"}, "device_types": ["ios"]}
Do you have a tutorial for sending a notification to an alias instead of a device token?