다음을 통해 공유


백엔드에서 REST API 사용

 

설명한 것 처럼 등록 관리, 일반적으로 응용 프로그램 백엔드에서 알림을 보내고 등록 관리를 수행할 수 있습니다. 이미 있기 때문에 노드에 대 한 Azure SDK에 Node.js에 대 한 REST 래퍼가이 섹션에서는 Java에서 예를 보여줍니다.

알림 보내기

알림을 보내는 REST API는 /yourHub/messages에서 특수 헤더가 있는 단순 POST입니다. 플랫폼 기본 형식으로 알림을 보낼 때 본문은 알림을 받을 플랫폼에 따라 달라집니다. 추가 헤더는 다음과 같습니다.

  • ServiceBusNotification 형식: 플랫폼(기본 알림을 보내는 경우) 또는 "템플릿"이 템플릿 알림을 보내도록 지정합니다.

  • Servicebusnotification-tags (선택 사항): 태그(또는 태그 식)가 대상 등록 집합을 정의하도록 지정합니다. 이 헤더가 없으면 알림 허브는 모든 등록에 브로드캐스트합니다.

다른 헤더에 지정 된 플랫폼 특정 기능에 대 한 지원 되는 알림 허브 REST API 설명서입니다.

다음 Java 코드는 Apache HttpClient를 사용하여 Windows 스토어 앱에 기본 알림을 보냅니다.

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(); } }  

마찬가지로, 다음 코드도 템플릿 알림을 보냅니다.

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; }  

에 대한 자세한 내용은 참조를 다른 플랫폼에 알림을 보내는 알림 허브 REST API합니다.

등록 만들기 및 업데이트

등록을 만들고 업데이트하려면 등록 XML 형식의 직렬화 및 역직렬화가 필요합니다.등록 만들기 API 항목에는 여러 종류의 등록 (네이티브 및 모든 플랫폼에 대 한 서식 파일)을 만들기 위한는 XML 형식을 보여줍니다.

중요

XML 요소는 표시된 것과 순서가 같아야 합니다.

다음은 간단한 문자열 연결을 사용 하 여 등록 XML 페이로드를 만드는 Java로 등록을 만들어의 예 및 Apache Digester 결과 구문 분석할 수 있습니다. 이전에 언급했듯이 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(); } }  

getXml() 기본 Windows 등록에 대 한 메서드는 다음과 같습니다.

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(); }

예에서 기타 등록 유형에 대 한 메서드를 쉽게 추측할 수는 등록 만들기 API 항목입니다.

와 같은 읽기 전용 속성을 포함 하는 생성의 결과 포함 하는 응답 RegistrationId, ETag, 및 ExpirationTime합니다. 다음 코드 예제를 사용 하 여 결과 구문 분석 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); }  

사항에 유의 Create 호출이 반환 된 registrationId, 검색, 업데이트 또는 등록을 삭제 하는데 사용 되는 합니다.

참고

위 코드 조각의 서브 클래스 라고 가정 Registration 라는 WindowsRegistrationDescription합니다.

실행 하 여 등록을 업데이트할 수는 PUT 호출에 /yourhub/등록 / {registrationId}.If-match 헤더 제공 하는데 사용 되는 ETag (낙관적 동시성을 지원 합니다.) 하거나 간단히 "*" 항상 덮어쓸 수 있습니다. 하는 경우는 If-match 헤더가 없으면, 작업 수행 "upsert" (항상 현재 등록을 덮어쓰거나 하나에 제공 된 만들기 registrationId 없는 경우). 예를 들면 다음과 같습니다.

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(); } }  

등록 삭제 유사한 작업이입니다.

등록 검색

등록을 검색할 때 GET 호출에서 발급 된 /registrations/{registrationId}합니다. 다음 REST API에 지정된 대로 등록 컬렉션을 검색합니다.

다음 옵션을 지정 해야는 $top 등록 수를 제한 하는 매개 변수를 반환 합니다. 해당 쿼리에 대 한 등록이 있는 경우에 다음 X-MS-ContinuationToken 헤더가 반환 되며,이 검색 하 여 나머지 등록을 계속 후속 호출에 전달할 수 있습니다. 또한 이전에 언급된 API 항목에서처럼 본문 형식이 이제 XML Atom 피드입니다.

다음 Java 코드는 태그가 있는 모든 등록을 검색합니다.

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(); } }  

이 코드는 CollectionResult 는 선택적 연속 토큰와 함께 등록 집합을 캡슐화 합니다.

다음 코드에서는 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); }