Joke Collection Website - Public benefit messages - How to call jpush push java background
How to call jpush push java background
Original works can be reprinted, but please indicate the source address blogs.com/V1haoge/p/6439313.html
There are two ways to implement Aurora push in the Java background. One is to use The push request API provided by Jiguang Push is /v3/push, and the other is to use the officially provided third-party Java SDK. Here is the implementation code of the first method of push: import?org.apache./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 with alias "? ?alias? ?"!");
JSONObject?error?=?JSONObject.fromObject(resData.get("error"));
log.info("The error message is: "? ?error.get("message").toString());
}
log.info(" The information with the alias "? ?alias? ?" was pushed successfully! ");
}catch(Exception?e){
log.error("For the alias "?" ?alias? ?"The information push failed!", e);
}
}
/** *?Assemble the special json string for Aurora 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
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 Aurora 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?.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 two: use Java?SDK */
@SuppressWarnings({?"deprecation",?"restriction"?})
public?class?JiguangPush?{
private ?static?final?Logger?log?=?LoggerFactory.getLogger(JiguangPush.class);
priv
ate?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?amp;amp;?result.isResultOK()){
log .info("Information for alias"? ?alias? ?" was pushed successfully!");
}else{
log.info("For alias"? ?alias? ?"The information push failed!");
}
}
/** *? Generate the 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()
p>.setApnsProduction(false)//true-push the production environment?false-push the development environment (test 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 Java SDK to implement push is very simple, the amount of code is small, and it is not difficult to understand. The official SDK A lot of the content mentioned in the article has been implemented. We just need to configure the information and then initiate the push. It should be noted that when using the second method, you need to import the jar package provided by Jiguang official website.
Add directly to the pom file in maven: lt;dependencygt;
lt;groupIdgt;cn.jpush.apilt;/groupIdgt;
lt; artifactIdgt;jpush-clientlt;/artifactIdgt;
lt;versiongt;3.2.15lt;/versiongt;
lt;/dependencygt; Note: A jar package is very likely to appear here Conflict: I have forgotten the specific package. It seems to be a log package. You can delete it after you find it.
Originally, our project was implemented in the second way, but in the end we found a problem when submitting the code, that is, although we only brought in the three jar packages provided by the official website, the last one According to statistics, 80 jar packages have been added for no reason. Submitting so many jar packages is too bloated and unrealistic, so the plan was temporarily changed and the first method was used for encoding.
The code uses an alias method for push, and the alias needs to be set on the mobile APP. It is best to set it after the user logs in, so that as long as the user logs in once, its bound alias will be It 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 Aurora server. This information has a storage time limit, which defaults to one day. As long as the user logs in to the mobile APP, the Aurora server will automatically push the information to the corresponding alias. On the mobile phone, it can be seen that the information is not pushed directly to the mobile phone by us the day after tomorrow, but through the transfer station of the Aurora server, and this is officially the work of Aurora. Note: Here is a tip. When setting this alias, you can actually directly set the user ID as an alias. It is convenient and safe. You don’t have to think of ways to generate a unique string for identification, or even need to set it in the background database. New fields are added to the user table.
- Related articles
- Selected short messages in rainy season
- What is the personality and psychology of people whose SMS inbox and phone records are empty at any time?
- Can I use my mobile phone when I xbox abroad without a USB flash drive?
- Can you find someone in Japan?
- Can Fetion be sent to Unicom users?
- What should I do if I keep sending spam messages with telecom numbers?
- How to back up the address book and SMS on Apple's mobile phone?
- A word suitable for brothers: the friendship between brothers is a family relationship guarded by life.
- Sorry messages make you sorry and bring you great happiness.
- Is China Rural Credit Investment Co., Ltd. a fraud company?