0

我已经建立了一个简单的网站,其中包含一个带有 JavaScript onclick 方法的按钮,我想使用 Urban Airship 向我的手机发送推送通知。

如果我在 data 属性周围使用引号,我会得到“500(内部服务器错误)”。如果我不在 data 属性周围使用引号,我会从 Urban Airship 获得一个弹出授权窗口,我在其中写入我的应用程序密钥和主密钥。它似乎接受了这一点,但之后我得到一个“405(不允许的方法)”。

根据 Chrome 开发工具,两种方式都作为 GET 处理,即使它被指定为 POST(这是必需的)。有什么问题?

function sendButtonClick(){
    jQuery.ajax({
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        username:'my app key',
        password:'my app secret',
        url: 'https://go.urbanairship.com/api/push/broadcast/',
        data: {"android": {"alert": "alerttest", "extra": {"extra test": "extra value test"}}},
        dataType: 'jsonp',
    });
};

提前致谢!

4

2 回答 2

1

您使用的服务器端技术是什么?你必须从那里开始。基本上,您不能通过桌面浏览器进行跨域调用。您可以执行此操作的方法是,使用有效负载调用您的服务器端方法,然后让服务器端发送通知。这是我编写的 c# 示例代码。

 public interface INotification
{
    void Set(string deviceId, string alert, int? badge, string sound);
}

public class BaseNotification
{

    public List<string> Aliases { get; set; }
    public List<string> Tags { get; set; }
}

 public class iOSNotification : BaseNotification, INotification
{
    public List<string> Device_Tokens { get; set; }
    public NotificationBody aps { get; set; }

    public iOSNotification()
    {
        Device_Tokens = new List<string>();
    }

    public void Set(string deviceId, string alert, int? badge, string sound)
    {
        Device_Tokens.Add(deviceId);
        aps = new NotificationBody
        {
            Alert = alert,
            Badge = badge.HasValue ? badge.Value : 0,
            Sound = sound
        };
    }
}

//in a static extensions
 public static string ToJSONString<T>(this IEnumerable<T> items)
   {
        var jsonString =  JsonConvert.SerializeObject(items, Formatting.Indented, new JsonSerializerSettings
            {
                ContractResolver = new LowerCaseContractResolver(),
                NullValueHandling = NullValueHandling.Ignore
            });

        jsonString = jsonString.Replace("\r\n", string.Empty);

        return jsonString;

    }



protected internal void SendPushNotification(List<INotification> payLoad, string uriKey) {

        var json = payLoad.ToJSONString();
        var Uri = GetAppSettings(uriKey);
        var encoding = new UTF8Encoding();

        var contentLength = encoding.GetByteCount(json);

        var request = (WebRequest)WebRequest.Create(Uri);

        request.Method = "POST";
        CredentialCache credentialCache = new CredentialCache();
        credentialCache.Add(new Uri(Uri), "Basic", GetCredentials());

        request.Credentials = credentialCache;

        request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(_username + ":" + _password)));
        request.ContentType = "application/json";
        request.ContentLength = contentLength;


        using (var stream = request.GetRequestStream()) {

            stream.Write(encoding.GetBytes(json), 0, contentLength);
            stream.Close();

            var response = request.GetResponse();

            response.Close();
        }

    }
于 2013-04-18T14:52:33.073 回答
0

您将无法在任何浏览器、移动设备或桌面上发布跨域。您最好的选择是在您的服务器上设置一个端点,该端点需要来自 jQuery 的 POST 请求(例如 yoursite.com/message/broadcast)。然后,在服务器上,对https://go.urbanairship.com/api/push/broadcast进行 POST 。当它响应时,将响应作为您的响应发回。

你最好把你的 API 主密码保存在你的服务器上。

NOTE: You'll want to make sure you don't include the API password on your client. In fact, I suggest leaving the auth header out in the client, and then add it on your server before sending the request off to UrbanAirship. So even if you could POST cross-domain (aka you were building an iOS native Cocoa application), you're still better off keeping the secure credentials on your server instead of the device)

例如,使用Sails(javascript / Node.js 服务器):

// api/MessageController.js
module.exports = {
  broadcast: function (req,res) {

   // Your message for UrbanAirship should be sent as JSON in req.body
   // e.g. req.body === '{ "android": { "alert": "foo" } } '

    var httpRequest = require('request');
    httpRequest({
      url: 'https://go.urbanairship.com/api/push/broadcast/',
      json: 'true',
      auth: {
        'user': 'YOUR_API_KEY',
        'pass': 'YOUR_MASTER_SECRET',
        'sendImmediately': true
      },
      body: req.body
    }, function (err) {

      // Send confirmation back to jQuery of either success (200) or error (500)
      if (err) res.send(err, 500);
      else res.send(200);

    });
  }
};
于 2013-04-20T21:01:18.037 回答