JSON有效负载URL问题android

时间:2011-10-11 10:38:00

标签: android json http-status-code-400

我正在使用针对Android的Urban Airship推送通知。在那,我想使用广播发送所有用户的通知。在使用它时,我收到400错误的请求错误。

请告诉我代码中的错误:

Authenticator.setDefault(new Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                       return new PasswordAuthentication("sixxxxxxw","YSxxxxxxxxxx:Fxxxxxxxxxxxx".toCharArray());
                       }
                });

           URL url = new URL("https://go.urbanairship.com/api/airmail/send/broadcast/");
           HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
           connection.setRequestMethod("POST");
           connection.setDoOutput(true);
           connection.setDoInput(true);
           connection.setUseCaches(false);


           connection.setRequestProperty("Content-Type","application/json");
           //connection.setRequestProperty("Content-Length", Integer.toString(data.length()));
           JSONObject json = new JSONObject();
           json.put("title","My title");
           json.put("message","My message");



           try {
               output = connection.getOutputStream();
               output.write(json.toString().getBytes());
             } finally {
               if (output != null) { output.close(); }
             }

             int status = ((HttpURLConnection) connection).getResponseCode();
             System.out.println("status is..." + status);

我想发送的实际JSON Payload是:

{
    "push": {
        "aps": {
            "alert": "New message!"
        }
    },
    "title": "Message title",
    "message": "Your full message here.",
    "extra": {
        "some_key": "some_value"
    }
}

或者如果您有sample code for using urban airpship push notifications broadcast api请在这里分享。

如何使用HttpsURLConnection将此payload发送到服务。?

谢谢

2 个答案:

答案 0 :(得分:1)

这就是您“构建”JSON PayLoad的方式:

        JSONObject json = new JSONObject();
        JSONObject push = new JSONObject();
        JSONObject aps = new JSONObject();
        JSONObject extra = new JSONObject();
        aps.put("alert", "New message!");
        push.put("aps", aps);
        json.put("push", push);
        json.put("title","My title");
        json.put("message","My message");
        extra.put("some_key","some_value");
        json.put("extra", extra);

答案 1 :(得分:0)

您在代码中创建的JSON只包含标题和消息。缺乏

"push": {
    "aps": {
        "alert": "New message!"
    }
},

"extra": {
    "some_key": "some_value"
}

不是吗?