gpt4 book ai didi

javascript - 通过 javascript 的 gcm 消息

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:03:45 28 4
gpt4 key购买 nike

我想通过 javascript 代码发送 gcm 消息。为此,我们需要发布一个 json 对象。

url 和 json 对象格式在 gcm 文档中给出:http://developer.android.com/google/gcm/adv.html

出于测试目的,我编写了一个完美运行的 Java 代码。但是javascript代码不起作用。如果有人有一些示例工作代码(gcm 的 javascript),请发布。

String body = "registration_id=proper_id&data.number=12345678";
byte[] bytes = body.getBytes();
HttpURLConnection conn = getConnection(url);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
conn.setRequestProperty("Authorization", "key=" + key);
OutputStream out = conn.getOutputStream();
out.write(bytes);

JavaScript 代码:

var http = new XMLHttpRequest();
var url = "https://android.googleapis.com/gcm/send";
http.onreadystatechange = function() {
if (http.readyState == 4 && http.status == 200) { document.getElementById("target").innerHTML = http.responseText;
}
}
http.open("POST", url, false);
http.setRequestHeader("Content-type", "application/json");
http.setRequestHeader("Authorization", "key=proper_api_key");
var data = '{ "collapse_key": "qcall","time_to_live": 108, "delay_while_idle": true,"data": {"number":"12345678"},"registration_ids":["proper_id"]}';
http.send(data);

最佳答案

由于 Same-origin Policy,这将不起作用

In computing, the same-origin policy is an important security concept for a number of browser-side programming languages, such as JavaScript. The policy permits scripts running on pages originating from the same site – a combination of scheme, hostname, and port number – to access each other's methods and properties with no specific restrictions, but prevents access to most methods and properties across pages on different sites.

简而言之:您不能将 HTTP Post 发送到您的脚本执行所在域以外的其他域。

在这里你可以看到 rules of the Same-origin Policy

您需要使用您的 Java 代码,或者如果您的主机不支持 Java,您可以使用 PHP。 This question about GCM and PHP似乎有一个适用于 GCM 的有效 PHP 脚本。

祝你好运

关于javascript - 通过 javascript 的 gcm 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15958174/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com