Share via


Utilizzo di API REST da un back-end

 

Come spiegato in gestione delle registrazioni, in genere il back-end dell'applicazione invia notifiche e può eseguire la gestione delle registrazioni. Poiché esiste già un wrapper REST per Node. js in Azure SDK for Node, in questa sezione vengono illustrati esempi in Java.

Invio di notifiche

L'API REST per l'invio di notifiche è un semplice POST su /yourHub/messages, con speciali intestazioni. Quando si inviano notifiche in un formato nativo della piattaforma, il corpo sarà quello specifico di piattaforma da inviare. Le ulteriori intestazioni sono:

  • ServiceBusNotification-Format: specifica che la piattaforma (in caso di invio di una notifica nativa) o il "modello" deve inviare una notifica modello.

  • ServiceBusNotification-Tags (facoltativo): specifica il tag (o l'espressione tag) che definisce il set di registrazioni di destinazione. Se questa intestazione non è presente, l'hub notifiche esegue la trasmissione a tutte le registrazioni.

Sono supportate altre intestazioni per funzionalità specifiche di piattaforma, come indicato nella documentazione di API REST degli hub di notifica.

Il seguente codice Java invia una notifica nativa ad app di Windows Store (mediante Apache HttpClient):

public Notification createWindowsNotification(String body) { Notification n = new Notification(); n.body = body; n.headers.put("ServiceBusNotification-Format", "windows"); if (body.contains("<toast>")) n.headers.put("X-WNS-Type", "wns/toast"); if (body.contains("<tile>")) n.headers.put("X-WNS-Type", "wns/tile"); if (body.contains("<badge>")) n.headers.put("X-WNS-Type", "wns/badge"); if (body.startsWith("<")) { n.contentType = ContentType.APPLICATION_XML; } return n; } public void sendNotification(Notification notification, String tagExpression) { HttpPost post = null; try { URI uri = new URI(endpoint + hubPath + "/messages"+APIVERSION); post = new HttpPost(uri); post.setHeader("Authorization", generateSasToken(uri)); if (tagExpression != null && !"".equals(tagExpression)) { post.setHeader("ServiceBusNotification-Tags", tagExpression); } for (String header: notification.getHeaders().keySet()) { post.setHeader(header, notification.getHeaders().get(header)); } post.setEntity(new StringEntity(notification.getBody())); HttpResponse response = httpClient.execute(post); if (response.getStatusLine().getStatusCode() != 201) { String msg = ""; if (response.getEntity() != null && response.getEntity().getContent() != null) { msg = IOUtils.toString(response.getEntity().getContent()); } throw new RuntimeException("Error: " + response.getStatusLine() + " body: "+msg); } } catch (Exception e) { throw new RuntimeException(e); } finally { if (post != null) post.releaseConnection(); } }  

In modo analogo, il codice riportato di seguito invia una notifica modello:

public Notification createTemplateNotification(Map<String, String> properties) { Notification n = new Notification(); StringBuffer buf = new StringBuffer(); buf.append("{"); for (Iterator<String> iterator = properties.keySet().iterator(); iterator.hasNext();) { String key = iterator.next(); buf.append("\""+ key + "\":\""+properties.get(key)+"\""); if (iterator.hasNext()) buf.append(","); } buf.append("}"); n.body = buf.toString(); n.contentType = ContentType.APPLICATION_JSON; n.headers.put("ServiceBusNotification-Format", "template"); return n; }  

Per altre informazioni sull'invio di notifiche ad altre piattaforme, vedere API REST degli hub di notifica.

Creazione e aggiornamento di registrazioni

Per creare e aggiornare registrazioni è necessario eseguire la serializzazione e deserializzazione del formato XML della registrazione. Nell'argomento sull'API Creare una registrazione vengono illustrati i formati XML per la creazione di diversi tipi di registrazioni (native e modello per ogni piattaforma).

Importante

Gli elementi XML devono trovarsi nello stesso ordine illustrato.

Di seguito è riportato un esempio di creazione di una registrazione in Java, in cui vengono utilizzate semplici concatenazioni di stringhe per creare il payload XML di registrazione e Apache Digester per analizzare il risultato. Come indicato in precedenza, funziona bene qualsiasi approccio di serializzazione e deserializzazione XML.

public Registration createRegistration(Registration registration) { HttpPost post = null; try { URI uri = new URI(endpoint + hubPath + "/registrations"+APIVERSION); post = new HttpPost(uri); post.setHeader("Authorization", generateSasToken(uri)); StringEntity entity = new StringEntity(registration.getXml(),ContentType.APPLICATION_ATOM_XML); entity.setContentEncoding("utf-8"); post.setEntity(entity); HttpResponse response = httpClient.execute(post); if (response.getStatusLine().getStatusCode() != 200) throw new RuntimeException("Error: " + response.getStatusLine()); return Registration.parse(response.getEntity().getContent()); } catch (Exception e) { throw new RuntimeException(e); } finally { if (post != null) post.releaseConnection(); } }  

Il metodo getXml() per le registrazioni native di Windows ha il seguente aspetto:

private static final String WNS_NATIVE_REGISTRATION = "<?xml version=\"1.0\" encoding=\"utf-8\"?><entry xmlns=\"http://www.w3.org/2005/Atom\"><content type=\"application/xml\"><WindowsRegistrationDescription xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"https://schemas.microsoft.com/netservices/2010/10/servicebus/connect\">{0}<ChannelUri>{1}</ChannelUri>
</WindowsRegistrationDescription>
</content>
</entry>"; public String getXml() { String xml = WNS_NATIVE_REGISTRATION.replaceFirst("\\{1\\}", channelUri.toString()); xml = xml.replaceFirst("\\{0\\}", getTagsXml()); return xml.toString(); }

È possibile derivare facilmente i metodi per altri tipi di registrazioni dagli esempi riportati nell'argomento sull'API Creare una registrazione.

La risposta contiene il risultato della creazione, incluse le proprietà di sola lettura quali RegistrationId, ETag e ExpirationTime. Il seguente esempio di codice analizza il risultato mediante Apache Digester:

public static Registration parse(InputStream content) throws IOException, SAXException { Digester digester = new Digester(); digester.addObjectCreate("*/WindowsRegistrationDescription", WindowsRegistration.class); digester.addCallMethod("*/RegistrationId", "setRegistrationId", 1); digester.addCallParam("*/RegistrationId", 0); digester.addCallMethod("*/ETag", "setEtag", 1); digester.addCallParam("*/ETag", 0); digester.addCallMethod("*/ChannelUri", "setChannelUri", 1); digester.addCallParam("*/ChannelUri", 0); digester.addCallMethod("*/Tags", "setTagsFromString", 1); digester.addCallParam("*/Tags", 0); digester.addCallMethod("*/BodyTemplate", "setBodyTemplate", 1); digester.addCallParam("*/BodyTemplate", 0); digester.addCallMethod("*/WnsHeader", "addHeader", 2); digester.addCallParam("*/WnsHeader/Header", 0); digester.addCallParam("*/WnsHeader/Value", 1); return digester.parse(content); }  

Si noti che la chiamata Create restituisce un registrationId, che viene utilizzato per recuperare, aggiornare o eliminare la registrazione.

Nota

Il frammento precedente presuppone che esista una sottoclasse di Registration denominata WindowsRegistrationDescription.

È possibile aggiornare una registrazione generando una chiamata PUT su /yourhub/registrations/{IdRegistrazione}. L'intestazione If-Match viene utilizzata per fornire un ETag (che supporti la concorrenza ottimistica) o semplicemente un asterisco ("*") da sovrascrivere sempre. Se l'intestazione If-Match non è presente, l'operazione esegue un "upsert", sovrascrivendo sempre la registrazione corrente o creandone una con l'IdRegistrazione fornito, nel caso non sia presente. Ad esempio:

public Registration updateRegistration(Registration registration) { HttpPut put = null; try { URI uri = new URI(endpoint + hubPath + "/registrations/"+registration.getRegistrationId()+APIVERSION); put = new HttpPut(uri); put.setHeader("Authorization", generateSasToken(uri)); put.setHeader("If-Match", registration.getEtag()==null?"*":"W/\""+registration.getEtag()+"\""); put.setEntity(new StringEntity(registration.getXml(),ContentType.APPLICATION_ATOM_XML)); HttpResponse response = httpClient.execute(put); if (response.getStatusLine().getStatusCode() != 200) throw new RuntimeException("Error: " + response.getStatusLine()); return Registration.parse(response.getEntity().getContent()); } catch (Exception e) { throw new RuntimeException(e); } finally { if (put != null) put.releaseConnection(); } }  

Elimina registrazione è un'operazione simile.

Recupero di registrazioni

Quando si recupera una registrazione, eseguire una chiamata GET su /registrations/{registrationId}. Verrà recuperato un insieme di registrazioni, come specificato nelle seguenti API REST:

Sarà quindi possibile specificare un parametro $top per limitare il numero di registrazioni restituite. Se sono presenti più registrazioni per la query in questione, verrà restituita un'intestazione X-MS-ContinuationToken, che è possibile passare alle chiamate successive, per continuare a recuperare le altre registrazioni. Si noti anche che il formato del corpo è ora un feed Atom XML, come illustrato negli argomenti sulle API prima citati.

Il seguente codice Java recupera tutte le registrazioni contenenti il tag:

private CollectionResult retrieveRegistrationByTag() { String queryUri = endpoint + hubPath + "/tags/"+tag+"/registrations"+APIVERSION; HttpGet get = null; try { URI uri = new URI(queryUri); get = new HttpGet(uri); get.setHeader("Authorization", generateSasToken(uri)); HttpResponse response = httpClient.execute(get); if (response.getStatusLine().getStatusCode() != 200) throw new RuntimeException("Error: " + response.getStatusLine()); CollectionResult result = Registration.parseRegistrations(response.getEntity().getContent()); Header contTokenHeader = response.getFirstHeader("X-MS-ContinuationToken"); if (contTokenHeader !=null) { result.setContinuationToken(contTokenHeader.getValue()); } return result; } catch (Exception e) { throw new RuntimeException(e); } finally { if (get != null) get.releaseConnection(); } }  

In questo codice, un CollectionResult incapsula un set di registrazioni insieme a un token di continuazione facoltativo.

Il seguente codice utilizza Apache Digester:

public static CollectionResult parseRegistrations(InputStream content) throws IOException, SAXException { Digester digester = new Digester(); // add all rules for parsing single registrations digester.addObjectCreate("feed", CollectionResult.class); digester.addSetNext("*/WindowsRegistrationDescription", "addRegistration"); // add rules for other types of registrations (if required) return digester.parse(content); }