1. 程式人生 > >java實現window phone推送通知

java實現window phone推送通知

package com.windowphone.text;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;

public class HttpPost {

 private String xml;
 private String url;

 public HttpPost(String url, String xml) {
  this.xml = xml;
  this.url = url;
 }

 private void Send() {
  
  HttpURLConnection con = null;
  URL url = null;
  try {
   url = new URL(this.url);
   con = (HttpURLConnection) url.openConnection();
   con.setRequestMethod("POST");
   con.setDoOutput(true);
   con.setDoInput(true);
   con.setUseCaches(false);
   
   //全球唯一的ID,型別:eb84a429-1ac6-46e2-b3f3-51929fd17648
   String guid = UUID.randomUUID().toString();  
   con.setRequestProperty("X-MessageID",guid);
   con.setRequestProperty("Content-Type","text/xml;charset=utf-8");
   
   //①Raw Notification模式
   //3:立刻傳送 13:等待450秒傳送 23:等待900秒傳送
   con.setRequestProperty("X-NotificationClass", "3");
   
   
   //②Toast Notification模式
   //2:立刻傳送 12:等待450秒傳送 22:等待900秒傳送
//   con.setRequestProperty("X-WindowsPhone-Target", "toast");
//   con.setRequestProperty("X-NotificationClass", "2");
   
   //③Tile Notification模式
   //1:立刻傳送 11:等待450秒傳送 21:等待900秒傳送
//            con.setRequestProperty("X-WindowsPhone-Target", "token");
//            con.setRequestProperty("X-NotificationClass", "1");
            
   OutputStream out = con.getOutputStream();
   //在此要特別的小心,傳送位元流,要把獲取位元組碼改為utf-8,不然中文會亂碼
   out.write(this.xml.getBytes("utf-8"));
   out.flush();
   
   //輸出微軟伺服器response的情況,正常輸出OK
   System.out.println("response:   "+con.getResponseMessage());
   
   out.close();
   con.disconnect();
  } catch (ConnectException ce) {
  } catch (IOException ie) {
  } catch (Exception e) {
  }
 }

 
 public static void main(String[] args) {
  
  //這裡直接複製window phone 應用註冊微軟的Uri
  String uri = "http://db3.notify.live.net/throttledthirdparty/01.00/AAGKzo1xh_AfR4Ia6ePTklzoAgAAAAADAQAAAAQUZm52OjIzOEQ2NDJDRkI5MEVFMEQ";
  
  ///①Raw Notification模式
  String rawMessage = "hitler 林楚金!";
  
  //②Toast Notification模式,固定模式,Text1和Text2兩個引數
  String toastMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
        "<wp:Notification xmlns:wp=\"wpNotification\">" +
        "<wp:Toast>" +
        "<wp:Text1>123</wp:Text1>" +
        "<wp:Text2>林楚金</wp:Text2>" +
        "</wp:Toast>" +
        "</wp:Notification>";
  
  //③Tile Notification模式,固定模式,BackgroundImage背景圖片,count數量,Title小標題
  String tileMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
        "<wp:Notification xmlns:wp=\"wpNotification\">" +
        "<wp:Tile>" +
        "<wp:BackgroundImage>/Images/天晴.jpg</wp:BackgroundImage>" +
        "<wp:Count>2</wp:Count>" +
        "<wp:Title>fuck 林楚金</wp:Title>" +
        "</wp:Tile>" +
        "</wp:Notification>";
    
  HttpPost post = new HttpPost(uri,rawMessage);
  
  post.Send();
 }

}