Christer Nordvik
Christer Nordvik

Reputation: 2528

How to use REST API for sending messages to Azure Notification Hub from Java/GAE

I have successfully implemented calling GAE -> Azure Mobile Services -> Azure Notification HUB.

But I want to skip the Mobile Services step and call the notification HUB directly and I can't figure out how to send the authorization token. The returned error is:

Returned response: <Error><Code>401</Code><Detail>MissingAudience: The provided token does not 
specify the 'Audience'..TrackingId:6a9a452d-c3bf-4fed-b0b0-975210f7a13c_G14,TimeStamp:11/26/2013 12:47:40 PM</Detail></Error>

Here is my code:

    URL url = new URL("https://myapp-ns.servicebus.windows.net/myhubbie/messages/?api-version=2013-08");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setConnectTimeout(60000);
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);        
    connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
    connection.setRequestProperty("Authorization","WRAP access_token=\"mytoken_taken_from_azure_portal=\"");
    connection.setRequestProperty("ServiceBusNotification-Tags", tag);


    byte[] notificationMessage = new byte[0];
    try 
    {
        notificationMessage = json.getBytes("UTF-8");
    } 
    catch (UnsupportedEncodingException e) 
    {           
        e.printStackTrace();
        log.warning("Error encoding toast message to UTF8! Error=" + e.getMessage());
    }

    connection.setRequestProperty("Content-Length", String.valueOf(notificationMessage.length));        
    OutputStream ostream = connection.getOutputStream();        
    ostream.write(notificationMessage);
    ostream.flush();
    ostream.close();

    int responseCode = connection.getResponseCode();

Upvotes: 3

Views: 2734

Answers (1)

Elio Damaggio
Elio Damaggio

Reputation: 860

The authorization header has to contain a token specially crafted for each individual request. The data you are using is the key you have to use to generate such a token.

Please follow the instructions on : http://msdn.microsoft.com/en-us/library/dn495627.aspx to create a token for your requests.

Final note, if you are using Java, you can use the code in this public repo https://github.com/fsautomata/notificationhubs-rest-java. It contains a fully functional REST wrapper for Notification Hubs. It is not Microsoft official but works and implements the above specs.

Upvotes: 1

Related Questions