Two implementation methods of Java background server to realize Jiguang push

Reprinted from:     http://www.cnblogs.com/V1haoge/p/6439313.html

There are two ways to implement Jiguang push in the Java background. One is to use the official push request API provided by Jiguang Push: https://api.jpush.cn/v3/push, and the other is to use the official third-party Java SDK. , here is the implementation code of the first push method:


The first push method: the push request API officially provided by 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 com.alibaba.fastjson.JSONArray;
import net.sf.json.JSONObject;
import sun.misc.BASE64Encoder;

/**
 * java background aurora push method 1: use Http API
 * This method requires a custom http request to send the client: HttpClient
 */
@SuppressWarnings({ "deprecation", "restriction" })
public class JiguangPush {
    private static final Logger log = LoggerFactory.getLogger(JiguangPush.class);
    private String masterSecret = "xxxxxxxxxxxxxxxxxxxx";
    private String appKey = "xxxxxxxxxxxxxxxxxxx";
    private String pushUrl = "https://api.jpush.cn/v3/push";    
    private boolean apns_production = true;    
    private int time_to_live = 86400;
    private static final String ALERT = "Push information";    
    /**
     * Aurora push
     */
    public void jiguangPush(){
        String alias = "123456";//Declare alias
        try{
            String result = push(pushUrl,alias,ALERT,appKey,masterSecret,apns_production,time_to_live);
            JSONObject resData = JSONObject.fromObject(result);
                if(resData.containsKey("error")){
                    log.info("Failed to push information for alias " + alias + "!");
                    JSONObject error = JSONObject.fromObject(resData.get("error"));
                    log.info("The error message is: " + error.get("message").toString());
                }
            log.info("Successful push for information with alias " + alias + "!");
        }catch(Exception e){
            log.error("Failed to push information with alias " + alias + "!",e);
        }
    }
    
    /**
     * Assemble the dedicated json string for Jiguang push
     * @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();//Push target
        JSONArray alias1 = new JSONArray();
        alias1.add(alias);
        audience.put("alias", alias1);
        
        JSONObject notification = new JSONObject();//Notification content
        JSONObject android = new JSONObject();//android notification content
        android.put("alert", alert);
        android.put("builder_id", 1);
        JSONObject android_extras = new JSONObject();//android extra parameters
        android_extras.put("type", "infomation");
        android.put("extras", android_extras);
        
        JSONObject ios = new JSONObject();//ios notification content
        ios.put("alert", alert);
        ios.put("sound", "default");
        ios.put("badge", "+1");
        JSONObject ios_extras = new JSONObject();//ios extra parameters
        ios_extras.put("type", "infomation");
        ios.put("extras", ios_extras);
        notification.put("android", android);
        notification.put("ios", ios);
        
        JSONObject options = new JSONObject();//Set parameters
        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("notification", notification);
        json.put("options", options);
        return json;
        
    }
    
    /**
     * Push method - call Jiguang 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);
    }
    
    /**
     * Send Post request (json format)
     * @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);
        } catch (Exception e) {
            log.error("Accidentally encountered an exception when requesting communication [" + reqURL + "], the stack trace is as follows", e);  
        }finally{
            client.getConnectionManager().shutdown();
        }
        return result;
    }
     /**
    * BASE64 encryption tool
    */
     public static String encryptBASE64(String str) {
         byte[] key = str.getBytes();
       BASE64Encoder base64Encoder = new BASE64Encoder();
       String strs = base64Encoder.encodeBuffer(key);
         return strs;
     }
}

The second push method: Officially provided third-party Java SDK

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;


/**
 * java background aurora push method 2: use Java SDK
 */
@SuppressWarnings({ "deprecation", "restriction" })
public class JiguangPush {
    private static final Logger log = LoggerFactory.getLogger(JiguangPush.class);
    private static String masterSecret = "xxxxxxxxxxxxxxxxx";
    private static String appKey = "xxxxxxxxxxxxxxxx";
    private static final String ALERT = "Push information";    
    /**
     * Aurora push
     */
    public void jiguangPush(){
        String alias = "123456";//Declare alias
        log.info("User push information for alias" + alias + "");
        PushResult result = push(String.valueOf(alias),ALERT);
        if(result != null && result.isResultOK()){
            log.info("The information for the alias " + alias + " was pushed successfully!");
        }else{
            log.info("Failed to push information for alias " + alias + "!");
        }
    }
    
    /**
     * Generate Aurora push object PushPayload (using 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(false)//true - push production environment false - push development environment (test using parameters)
                        .setTimeToLive(90)//The expiration time of the message in the JPush server (test using parameters)
                        .build())
                .build();
    }
    /**
     * Aurora push method (using 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) {
            log.error("Connection error. Should retry later. ", e);
            return null;
        } catch (APIRequestException e) {
            log.error("Error response from JPush server. Should review and fix it. ", e);
            log.info("HTTP Status: " + e.getStatus());
            log.info("Error Code: " + e.getErrorCode());
            log.info("Error Message: " + e.getErrorMessage());
            log.info("Msg ID: " + e.getMsgId());
            return null;
        }    
    }
}

It can be seen that the method of using the Java SDK to implement push is very simple, the amount of code is small, and it is not difficult to understand. Many contents are implemented in the officially provided SDK. We just need to configure the information and then initiate the push. It should be noted that using the second method, you need to import the jar package provided by Jiguang's official website.

  Add directly to the pom file in maven:

<dependency>
    <groupId>cn.jpush.api</groupId>
    <artifactId>jpush-client</artifactId>
    <version>3.2.15</version>
</dependency>

  Note: It is very likely that there will be a jar package conflict here: I forgot which package, it seems to be a log package, you can delete it after you find it. I have recorded this jar package conflict problem, see the jar package conflict resolution for details

  Originally, our project was also implemented in the second way, but in the end, we found a problem when submitting the code, that is, although we only imported the jar package provided by the official website, the last statistic actually increased by 80+ for no reason. The submission of so many jar packages is too bloated and unrealistic, so the solution is temporarily changed and the first method is used for coding.

  The alias method is used in the code for push, which needs to be set on the mobile APP, preferably after the user logs in, so that as long as the user logs in once, its bound alias can be saved to the Jiguang server, and When we push, specify this alias to push the information to the corresponding user's mobile phone.

  In fact, when we initiate a push request, we just send the information to the Jiguang server. This information has a storage time limit. The default is one day. As long as the user logs in to the system using the mobile phone APP, the Jiguang server will automatically push the information to the mobile phone of the corresponding alias. It can be seen that the information is not directly pushed to the mobile phone by our background, but through the transfer station of the Jiguang server, and this is the official work of Jiguang.

  Note: Here is a trick. When setting this alias, you can directly set the user ID as an alias, which is convenient and safe. You don’t need to find a way to generate a unique string for identification, even in the background database. A new field has been added to the user table.



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325721702&siteId=291194637