java 后台 如何实现 谷歌 消息推送

第一步:申请GOOGLE 消息推送 KEY

第二步:

1、配置请求路径和KEY

java 后台 如何实现 谷歌 消息推送_第1张图片

2、写请求方法

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.ilogie.tms.vo.SendMsgData;

public class SendMessageUtil {
    
private static Logger logger =  LoggerFactory.getLogger(SendMessageUtil.class);
    
    private static String sendGoogleMsgUrl;
    private static String sendGoogleKey;
    
    @SuppressWarnings("all")
    public static void sendGoogleMessage(SendMsgData data){
        CloseableHttpClient client = HttpClients.createDefault();
        
        HttpPost httpPost = new HttpPost(sendGoogleMsgUrl);
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setHeader("Authorization", sendGoogleKey);
        
        try {
            
            logger.debug("消息推送路径:"+httpPost.getURI());
            
            GooglSend send = new SendMessageUtil.GooglSend();
            send.setTo(String.valueOf(data.getToId()));
            send.setData(data);
            
            String req = JSON.toJSONString(send);
            
            logger.debug("消息请求参数:"+req);
            
            StringEntity se = new StringEntity(req);
            
            httpPost.setEntity(se);
            
            CloseableHttpResponse resp = client.execute(httpPost);
            HttpEntity entity = resp.getEntity();
            
            String str2 = EntityUtils.toString(entity);
            logger.debug(str2);
        } catch (Exception e) {
            logger.debug("GOOGLE消息推送失败:"+e);
        }finally{
            try {
                client.close();
            } catch (IOException e) {
                logger.debug("GOOGLE消息推送关闭连接:"+e);
            }
        }
        
    }
    
    
    static class GooglSend{
        private String to;
        private SendMsgData Data;
        public String getTo() {
            return to;
        }
        public SendMsgData getData() {
            return Data;
        }
        public void setTo(String to) {
            this.to = to;
        }
        public void setData(SendMsgData data) {
            Data = data;
        }
        
    }
    
    
    public void setSendGoogleMsgUrl(String sendGoogleMsgUrl) {
        SendMessageUtil.sendGoogleMsgUrl = sendGoogleMsgUrl;
    }
    public void setSendGoogleKey(String sendGoogleKey) {
        SendMessageUtil.sendGoogleKey = sendGoogleKey;
    }

}

3、写测试类进行验证

java 后台 如何实现 谷歌 消息推送_第2张图片

你可能感兴趣的:(WEB,移动开发,GCM)