0

我正在使用 GCM(谷歌云消息传递)。我想从服务器端发送 J Son从服务器端到客户端。

请帮我解决这个问题。

这是我的服务器端代码

 public class GCMBroadcast extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static final String SENDER_ID = "";
    private static final String ANDROID_DEVICE = "";
    private List<String> androidTargets = new ArrayList<String>();
    public GCMBroadcast() {

        super();
        androidTargets.add(ANDROID_DEVICE);

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String collapseKey = "";
        String userMessage = "";

        try {
            userMessage = request.getParameter("Message");
            collapseKey = request.getParameter("CollapseKey");
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
        Sender sender = new Sender(SENDER_ID);
        Message message = new Message.Builder()


        .collapseKey(collapseKey)
        .addData("message", userMessage)
        .build();

        try {

            MulticastResult result = sender.send(message, androidTargets, 1);
            System.out.println("Response: " + result.getResults().toString());
            if (result.getResults() != null) {

                int canonicalRegId = result.getCanonicalIds();
                if (canonicalRegId != 0) {
                    System.out.println("response " +canonicalRegId );
                }
            } else {
                int error = result.getFailure();
                System.out.println("Broadcast failure: " + error);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }


        request.setAttribute("CollapseKey", collapseKey);
        request.setAttribute("Message", userMessage);

        request.getRequestDispatcher("XX.jsp").forward(request, response);

    }

}
4

1 回答 1

0

您的有效负载(Message通过调用添加到addData)只能是名称/值对。如果要发送JSON,可以JSON在此类名称/值对的值中放入一个字符串。然后你必须JSON在客户端自己解析它。

例如 :

.addData("message","{\"some_json_key\":\"some_json_value\"}")

于 2013-09-04T13:06:16.060 回答