第一步:申請GOOGLE 消息推送 KEY
第二步:
1、配置請求路徑和KEY
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、寫測試類進行驗證