直接从Java与Urban Airship进行通信

时间:2012-07-12 16:00:46

标签: java urbanairship.com

我有一个Java Web服务器,我希望通过它发送UA推送通知。我知道这可以通过UA的仪表板实现,但我想直接使用网络服务器与UA进行沟通。

我已阅读this documentation,并已审核过this SO question,但我仍然有点失落,无论从哪里开始。

任何人都可以请帮助我指出一个良好的起点吗?我是否需要导入任何特定的.jar文件等?

我一直在尝试调整以下代码段,但它似乎无法正常运行。我做错了什么?

URL mURL=new URL("https://go.urbanairship.com/api/push/broadcast");
HttpsURLConnection connection = (HttpsURLConnection)mURL.openConnection();
connection.setRequestMethod("POST");
JSONObject mPayload=new JSONObject();
JSONObject mPayload1=new JSONObject();
JSONObject mPayload2=new JSONObject();
mPayload1.put("extra", mPayload2);
mPayload1.put("alert", "hello world");
mPayload2.put("phonenumber", "12345");
mPayload.put("android", mPayload1);
System.out.println(mPayload.toString());
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.addRequestProperty("Content-Type","application/json;charset=UTF-8");
String authString = "**MY APP KEY**" + ":" + "**MASTER KEY**"; 

String authStringBase64 = new String(Base64.encodeBytes(authString.getBytes()));
authStringBase64 = authStringBase64.trim();

connection.addRequestProperty("Authorization", "Basic " + authStringBase64);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.write(mPayload.toString().getBytes());
wr.flush();
Log.d("print", "response code"+ connection.getResponseCode());

2 个答案:

答案 0 :(得分:0)

您只需要向您的urbanairship服务器发送POST请求并附上您的通知,包括适当编码的AppId和Secret密钥......

看起来您上面包含的链接是一个库,它将为您完成大部分工作。

示例代码,请注意:此示例中的PushNotificationObj是一个bean,其中包含推送正文的字段..

        URL url = new URL(URBAN_AIRSHIP_API_URL);
        HTTPRequest req = new HTTPRequest(url, HTTPMethod.POST);

        String authString = ApplicationProperties.getUrbanAirshipAppId() + ":" + ApplicationProperties.getUrbanAirshipMasterSecret();

        String authStringBase64 = new String(Base64.encodeBase64(authString.getBytes()));
        authStringBase64 = authStringBase64.trim();

        req.addHeader(new HTTPHeader("Content-Type", "application/json"));
        req.addHeader(new HTTPHeader("Authorization", "Basic " + authStringBase64));

        ObjectMapper mapper = new ObjectMapper();
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        mapper.writeValue(byteStream, new PushNotificationObj(userEmail, message));

        req.setPayload(byteStream.toByteArray());

然后发送请求......

答案 1 :(得分:0)

您可以尝试urbanairship4j(可在Google代码中找到)。它使用Google HTTP Java Client,因此可以在任何Java环境(包括AppEngine,Android等)上完美运行。