如何使用极光推送,java服务端向激光服务器进行推送

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/w960514/article/details/85233508

第一种:使用官方的sdk直接使用

/** 
 * <pre>项目名称:bsa-admin-api 
 * 文件名称:Test.java 
 * 包名:com.bsa.api.jiguang 
 * 创建日期:2018年12月10日下午2:30:19 
 * Copyright (c) 2018, [email protected] All Rights Reserved.</pre> 
 */  
package com.bsa.api.jiguang;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;

public class JPush {
	    private static String masterSecret = "888888888888888888";
	    private static String appKey = "88888888888888888888";
	    private static final String ALERT = "您安装在展厅的设备于2018-12-19 11:56:44发生丢失--测试9999"; 
	    private static final String ALIAS = "baosn"; 
	    public static void main(String[] args) {
	    	jiguangPush(ALIAS,ALERT);
		}
	    /**
	     * 极光推送
	     */
	    public static void jiguangPush(String alias, String alert){
	        System.out.println("对别名" + alias + "的用户推送信息");
	        PushResult result = push(String.valueOf(alias),alert);
	        if(result != null && result.isResultOK()){
	            System.out.println("针对别名" + alias + "的信息推送成功!");
	        }else{
	            System.out.println("针对别名" + alias + "的信息推送失败!");
	        }
	    }
	    
	    /**
	     * 生成极光推送对象PushPayload(采用java SDK)
	     * @param alias
	     * @param alert
	     * @return PushPayload
	     */
	    public static PushPayload buildPushObject_android_ios_alias_alert(String alias,String alert){
	        return PushPayload.newBuilder()
	                .setPlatform(Platform.android_ios())
	                .setAudience(Audience.alias(alias))
	                .setNotification(Notification.newBuilder()
	                        .addPlatformNotification(AndroidNotification.newBuilder()
	                                .addExtra("type", "infomation")
	                                .setAlert(alert)
	                                .build())
	                        .addPlatformNotification(IosNotification.newBuilder()
	                                .addExtra("type", "infomation")
	                                .setAlert(alert)
	                                .build())
	                        .build())
	                .setOptions(Options.newBuilder()
	                        .setApnsProduction(true)//true-推送生产环境 false-推送开发环境(测试使用参数)
	                        .setTimeToLive(90)//消息在JPush服务器的失效时间(测试使用参数)
	                        .build())
	                .build();
	    }
	    /**
	     * 极光推送方法(采用java SDK)
	     * @param alias
	     * @param alert
	     * @return PushResult
	     */
	    public static PushResult push(String alias,String alert){
	        ClientConfig clientConfig = ClientConfig.getInstance();
	        JPushClient jpushClient = new JPushClient(masterSecret, appKey, null, clientConfig);
	        PushPayload payload = buildPushObject_android_ios_alias_alert(alias,alert);
	        try {
	            return jpushClient.sendPush(payload);
	        } catch (APIConnectionException e) {
	            System.out.println("Connection error. Should retry later. ,,"+e);
	            return null;
	        } catch (APIRequestException e) {
	        	System.out.println("Error response from JPush server. Should review and fix it. "+e);
	            System.out.println("HTTP Status: " + e.getStatus());
	            System.out.println("Error Code: " + e.getErrorCode());
	            System.out.println("Error Message: " + e.getErrorMessage());
	            System.out.println("Msg ID: " + e.getMsgId());
	            return null;
	        }    
	    }
}

第二种使用调用api的方式

package com.bsa.api.jiguang;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import sun.misc.BASE64Encoder;

/**
 * java后台极光推送方式一:使用Http API
 * 此种方式需要自定义http请求发送客户端:HttpClient
 */
@SuppressWarnings({ "deprecation", "restriction" })
public class JiguangPush {
    private static final Logger log = LoggerFactory.getLogger(JiguangPush.class);
    private String masterSecret = "888888888888888888";
    private String appKey = "8888888888888";
    private String pushUrl = "https://bjapi.push.jiguang.cn/v3/push";    
    private boolean apns_production = true;    
    private int time_to_live = 86400;
//    private static final String ALERT = (new JiguangPush()).getMsg();   
        private static final String ALERT = "您安装在展厅的设备于2018-12-10 12:05:42发生低报";   
    private String msg;
    
    public static void main(String[] args) {
		JiguangPush jiguangPush = new JiguangPush();
		String alias = "baosn";//声明别名
		jiguangPush.jiguangPush(alias,"您安装在展厅的设备于2018-12-10 12:05:42发生低报");
	}
    /**
     * 极光推送
     */
    public String jiguangPush(String alias,String alert){
        try{
            String result = push(pushUrl,alias,alert,appKey,masterSecret,apns_production,time_to_live);
            System.out.println(result);
            JSONObject resData = JSONObject.fromObject(result);
                if(resData.containsKey("error")){
                	System.out.println();
                    System.out.println("针对别名为" + alias + "的信息推送失败!");
                    JSONObject error = JSONObject.fromObject(resData.get("error"));
                    System.out.println("错误信息为:" + error.get("message").toString());
                }
            System.out.println("针对别名为" + alias + "的信息推送成功!");
            return "ok";
        }catch(Exception e){
            System.out.println("针对别名为" + alias + "的信息推送失败!"+e);
            return "error";
        }
    }
    
    /**
     * 组装极光推送专用json串
     * @param alias
     * @param alert
     * @return json
     */
    public static JSONObject generateJson(String alias,String alert,boolean apns_production,int time_to_live){
        JSONObject json = new JSONObject();
        JSONArray platform = new JSONArray();//平台
        platform.add("android");
        platform.add("ios");
        
        JSONObject audience = new JSONObject();//推送目标
        JSONArray alias1 = new JSONArray();
        alias1.add(alias);
        audience.put("alias", alias1);
        /**
         * 这是关于通知的相关程序,通知的时候区分ios还是android
         */
        JSONObject notification = new JSONObject();//通知内容
        JSONObject android = new JSONObject();//android通知内容
        android.put("alert", alert);
        android.put("builder_id", 1);
        android.put("alert_type", -1);
        JSONObject android_extras = new JSONObject();//android额外参数
        android_extras.put("type", "1");
        android.put("extras", android_extras);
        
        JSONObject ios = new JSONObject();//ios通知内容
        ios.put("alert", alert);
        ios.put("sound", "default");
        ios.put("badge", "+1");
        JSONObject ios_extras = new JSONObject();//ios额外参数
        ios_extras.put("type", "1");
        ios.put("extras", ios_extras);
        notification.put("android", android);
        notification.put("ios", ios);
        
        
        /**
         * 这是关于消息的相关程序,推送消息的时候不区分ios还是android
         * 只需要是相关内容即可
         */
        JSONObject message = new JSONObject();//消息内容
        message.put("msg_content", alert);
        
        JSONObject options = new JSONObject();//设置参数
        //为用户保存推送信息时间
        options.put("time_to_live", Integer.valueOf(time_to_live));
        options.put("apns_production", apns_production);
        
        json.put("platform", platform);
        json.put("audience", audience);
//        json.put("message", message);
        json.put("notification", notification);
        json.put("options", options);
        return json;
        
    }
    
    /**
     * 推送方法-调用极光API
     * @param reqUrl
     * @param alias
     * @param alert
     * @return result
     */
    public static String push(String reqUrl,String alias,String alert,String appKey,String masterSecret,boolean apns_production,int time_to_live){
        String base64_auth_string = encryptBASE64(appKey + ":" + masterSecret);
        String authorization = "Basic " + base64_auth_string;
        return sendPostRequest(reqUrl,generateJson(alias,alert,apns_production,time_to_live).toString(),"UTF-8",authorization);
    }
    
    /**
     * 发送Post请求(json格式)
     * @param reqURL
     * @param data
     * @param encodeCharset
     * @param authorization
     * @return result
     */
    @SuppressWarnings({ "resource" })
    public static String sendPostRequest(String reqURL, String data, String encodeCharset,String authorization){
        HttpPost httpPost = new HttpPost(reqURL);
        HttpClient client = new DefaultHttpClient();
        HttpResponse response = null;
        String result = "";
        try {
             StringEntity entity = new StringEntity(data, encodeCharset);
             entity.setContentType("application/json");
             httpPost.setEntity(entity);
             httpPost.setHeader("Authorization",authorization.trim());
             response = client.execute(httpPost);
             result = EntityUtils.toString(response.getEntity(), encodeCharset);
             System.out.println(result);
        } catch (Exception e) {
            System.out.println("请求通信[" + reqURL + "]时偶遇异常,堆栈轨迹如下"+ e);  
        }finally{
            client.getConnectionManager().shutdown();
        }
        return result;
    }
     /** 
    * BASE64加密工具
    */
     public static String encryptBASE64(String str) {
         byte[] key = str.getBytes();
       BASE64Encoder base64Encoder = new BASE64Encoder();
       String strs = base64Encoder.encodeBuffer(key);
         return strs;
     }
	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}
}

说一下两种的区别吧,实际两种最终使用的时候都是调用了极光的api进行了推送。只不过不同的是如果我们使用api直接调用的时候咱们需要配置较多的参数,自己去组装什么消息message,通知notification啊之类的(通知是可以在状态栏上面显示的,而消息不能),包括要推送的平台也有三种,里面还有各种小参数去进行设置,这里面就不多说了。

猜你喜欢

转载自blog.csdn.net/w960514/article/details/85233508
今日推荐