Aurora message push server development implementation push

Source: Internet
Author: User
Tags ssl connection

The previously used Aurora manual input push content is then pushed to the client. Today, we encounter a relatively high push frequency and regular content, such as fact weather. In this way, we need to use our own server to automatically generate the push content.

In the official SDK documentation for a long time, finally found a bit similar interface, go in first look at: http://docs.jpush.cn/pages/viewpage.action? PageId = 2228302


We can see that the above two statements are very eye-catching. Let's take a look at what the rest api is encapsulated by it. Then click it to see it.


After reading the above two sentences, it seems that we are lucky. This should be the case.

Okay, let's go to the Java Development Section above: https://github.com/jpush/jpush-api-java-client

After reading the package for a long time, I have understood the meaning and helped us encapsulate it. Now we only need to download the jar package and the instance documentation it provides.


The resi api is described in more detail, such as parameters and frequency limits.

Okay. Let's take a look at the push messages and notifications, as shown in the following figure:


After entering, you can see the actually needed api. Here are descriptions of each method and parameter. If some friends still don't understand it, it's easy to download the sample code directly (no one will copy it)


I downloaded the official sample code and created a new project as follows:


Message sender code:

Package com. meritit. tuisong. service; import java. util. hashMap; import java. util. map; import cn. jpush. api. errorCodeEnum; import cn. jpush. api. IOSExtra; import cn. jpush. api. JPushClient; import cn. jpush. api. messageResult; public class JPushClientExample {private static final String appKey = "secret"; // required, for example, define static final String masterSecret = "0e0cc80c6f6a4703be C9ed191 "; //" 13ac09b17715bd117163d8a1 "; // required. Each application corresponds to a masterSecretprivate static JPushClient jpush = null;/*** Save the offline duration. In seconds. Supports up to 10 days (864000 seconds ). * 0 indicates that the message is not saved offline. That is, the user sends the message online immediately, and the current offline user will not receive the message. * If this parameter is not set, it indicates the default value. The default value is to save offline messages for one day (86400 seconds ). */Private static long timeToLive = 60*60*24; public static void main (String [] args) {/** Example1: initialization, which is sent to android and ios by default, set the offline message survival time * jpush = new JPushClient (masterSecret, appKey, timeToLive); * // ** Example2: only sent to android * jpush = new JPushClient (masterSecret, appKey, deviceEnum. android); * // ** Example3: only sent to IOS * jpush = new JPushClient (masterSecret, appKey, DeviceEnum. IOS); * // ** Exampl E4: Send only to android and set the offline message survival time * jpush = new JPushClient (masterSecret, appKey, timeToLive, DeviceEnum. android); */jpush = new JPushClient (masterSecret, appKey, timeToLive);/** whether to enable ssl secure connection; optional * parameter: true, false, the default is non-ssl connection * // jpush. setEnableSSL (true); // test whether to send a message or notify testSend ();} private static void testSend () {// in actual business, it is recommended that sendNo be an auto-increment number that can be processed by your own business. // Unless it needs to be overwritten, be sure not to use it again. For more information, see API documentation. Int sendNo = getRandomSendNo (); String msgTitle = "+; // jpush \" \ ""; String msgContent = "\\&; w \ "\" a -- [\ npush] ";/** extended parameters for IOS devices, * Set badge and sound */Map <String, object> extra = new HashMap <String, Object> (); IOSExtra iosExtra = new IOSExtra (10, "WindowsLogonSound.wav"); extra. put ("ios", iosExtra); // send notifications to all users. For more information, see MessageResult msgResult = jpush. sendCustomMessageWithAppKey (sendNo, msgTitle, msgContent );// MessageResult msgResult = jpush. sendNotificationWithAlias (sendNo, "a", msgTitle, msgContent); // overwrite the message of the specified msgId. msgId can be obtained from msgResult. getMsgid. // MessageResult msgResult = jpush. sendnotifwitwithappkey (sendNo, msgTitle, msgContent, 0, extra, msgResult. getMsgid (); if (null! = MsgResult) {System. out. println ("server returned data:" + msgResult. toString (); if (msgResult. getErrcode () = ErrorCodeEnum. NOERROR. value () {System. out. println (String. format ("sent successfully, sendNo = % s, messageId = % s", msgResult. getSendno (), msgResult. getMsg_id ();} else {System. out. println ("failed to send, error code =" + msgResult. getErrcode () + ", error message =" + msgResult. getErrmsg () ;}} else {System. out. println ("unable to get data");} public static final int MAX = Integer. MAX_VALUE; public static final int MIN = (int) MAX/2;/*** It is necessary to maintain the uniqueness of sendNo * It is very important to keep sendNo unique. * @ return sendNo */public static int getRandomSendNo () {return (int) (MIN + Math. random () * (MAX-MIN ));}}

The execution result is as follows:



Message Receiver code:

Package com. meritit. tuisong. service; import java. util. list; import cn. jpush. api. JPushClient; import cn. jpush. api. receive. receiveResult; public class extends eclientexample {private static final String appKey = "secret"; // required, for example, declare static final String masterSecret = "secret"; // "13ac09b17715bd117163d8a1 "; // public static void main (String [] ar Gs) {JPushClient = new JPushClient (masterSecret, appKey); String msgId = "1236722141"; String [] msgIds = {"1236722141", "910981248", "911034889 "}; // obtain a ReceiveResult receiveResult = JPushClient. getReceived (msgId); if (receiveResult = null) {System. out. println ("failed to get receive data! "+ ReceiveResult);} After else {// gson toJson, the NULL value field will be filtered out by System. out. println ("received result:" + receiveResult. toString ();} // obtain multiple lists <ReceiveResult> receiveResults = JPushClient. getReceiveds (msgIds); if (receiveResults = null) {System. out. println ("failed to get receive data! ") ;}Else {System. out. println (" obtained successfully: "+ receiveResults );}}}
Execution result:

The test has been successful. Let's take a look at how the source code is implemented. The rest is actually data encapsulation. Let's take a look at the key code.

MessageResult msgResult = jpush.sendCustomMessageWithAppKey(sendNo,msgTitle, msgContent);

View the source code as follows:

public MessageResult sendCustomMessageWithAppKey(int sendNo, String msgTitle, String msgContent) {CustomMessageParams p = new CustomMessageParams();p.setReceiverType(ReceiverTypeEnum.APPKEYS);return sendCustomMessage(p, sendNo, msgTitle, msgContent, null, null);}
The sendCustomMessage method is actually called.

protected MessageResult sendCustomMessage(CustomMessageParams p, int sendNo, String msgTitle, String msgContent, String msgContentType, Map<String, Object> extra) {if (null != msgContentType) {p.getMsgContent().setContentType(msgContentType);}if (null != extra) {p.getMsgContent().setExtra(extra);}return sendMessage(p, sendNo, msgTitle, msgContent);}
The null value is determined here, And the sendMessage method is actually called.

protected MessageResult sendMessage(MessageParams p, int sendNo, String msgTitle, String msgContent) {p.setSendNo(sendNo);p.setAppKey(this.getAppKey());p.setMasterSecret(this.masterSecret);p.setTimeToLive(this.timeToLive);p.setSendDescription(this.getSendDescription());for (DeviceEnum device : this.getDevices()) {p.addPlatform(device);}if (null != msgTitle) {p.getMsgContent().setTitle(msgTitle);}p.getMsgContent().setMessage(msgContent);return sendMessage(p);}
Here, the parameters are encapsulated into the message object and sendMessage is called.

protected MessageResult sendMessage(MessageParams params) {return httpClient.sendPush(BaseURL.ALL_PATH, enableSSL, params);}
Go to the sendPush method and check it out. Oh, I understand that the message is actually sent using an http request.

public MessageResult sendPush(final String path, final boolean enableSSL, final MessageParams messageParams) {MessageResult messageResult = ValidateRequestParams.vidateParams(messageParams);if(messageResult != null) return messageResult;String pushResult = sendPost(path, enableSSL, parse(messageParams),RequestTypeEnum.PUSH.value(),null);return gson.fromJson(pushResult, MessageResult.class);}
The key is the second line of code.

private String sendPost( String path, final boolean enableSSL, String params,Integer reqeustType,String authCode){return sendRequest(path, enableSSL, params, "POST", reqeustType,authCode);}

private String sendRequest(String path, final boolean enableSSL, String params,String method,Integer reqeustType,String authCode){HttpURLConnection conn = null;DataOutputStream outStream = null;StringBuffer sb = new StringBuffer();try {if (enableSSL) {initSSL();}URL url = new URL(BaseURL.getUrlForPath(path,enableSSL,reqeustType));conn = (HttpURLConnection) url.openConnection();conn.setConnectTimeout(DEFAULT_CONNECTION_TIMEOUT);conn.setReadTimeout(DEFAULT_SOCKET_TIMEOUT);conn.setUseCaches(false);conn.setDoOutput(true);conn.setRequestMethod(method);conn.setRequestProperty("Connection", "Keep-Alive");conn.setRequestProperty("Charset", CHARSET);if(authCode != null && !authCode.isEmpty()){conn.setRequestProperty("Authorization", authCode);}if(method.equals("POST")){byte[] data = params.getBytes(CHARSET);conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");conn.setRequestProperty("Content-Length", String.valueOf(data.length));outStream = new DataOutputStream(conn.getOutputStream());outStream.write(data);outStream.flush();}if (conn.getResponseCode() == 200) {logger.info("Congratulations!The request was successful. response status is 200");InputStream in = conn.getInputStream();InputStreamReader reader = new InputStreamReader(in, CHARSET);char[] buff = new char[1024];int len;while ((len = reader.read(buff)) > 0) {sb.append(buff, 0, len);}} else {logger.log(Level.WARNING,"Sorry!The request was fault. response " +"status = "+conn.getResponseCode()+",errormsg = "+conn.getHeaderField(0));String errmsg = "";if(reqeustType == RequestTypeEnum.RECEIVE.value()){errmsg = ErrorCodeEnum.errorMsg(conn.getResponseCode());errmsg = errmsg == null ? conn.getHeaderField(0) : errmsg;}else{errmsg = conn.getHeaderField(0);}BaseResult result = new BaseResult(errmsg,conn.getResponseCode());return result.toString();}}catch (SocketTimeoutException e) {logger.log(Level.SEVERE,"God! the server throw SocketTimeout Exception." +"please check it out the error message:"+e.getMessage());BaseResult baseResult = new BaseResult(e.getMessage().toString(),ErrorCodeEnum.CONNECTIONTIMEOUT.value());return baseResult.toString();}catch (ConnectException e) {logger.log(Level.SEVERE,"God! the server throw Connect Exception ." +"please check it out the error message:"+e.getMessage());BaseResult baseResult = new BaseResult(e.getMessage().toString(),ErrorCodeEnum.CONNECTIONREFUSED.value());return baseResult.toString();}catch (UnknownHostException e) {logger.log(Level.SEVERE,"God! the server throw UnknownHost Exception ." +"please check it out the error message:"+e.getMessage());BaseResult baseResult = new BaseResult(e.getMessage().toString(),ErrorCodeEnum.CONNECTIONREFUSED.value());return baseResult.toString();}catch (Exception e) {logger.log(Level.SEVERE,"God! the server throw exception." +"please check it out the error message:"+e.getMessage());BaseResult baseResult = new BaseResult(e.getMessage().toString(),ErrorCodeEnum.UnknownException.value());return baseResult.toString();} finally {if (null != outStream) {try {outStream.close();} catch (IOException e) {e.printStackTrace();}}if (null != conn) {conn.disconnect();}}return sb.toString();}

Those who have learned Android should be familiar with this! For example, for the URL request address, check the 9th lines of code.
URL url = new URL(BaseURL.getUrlForPath(path,enableSSL,reqeustType));

public  static String getUrlForPath(final String path,boolean enableSSL,Integer type) {return getHostname(enableSSL,type) + path;}

private static String getHostname(boolean enableSSL,Integer type) {if(type == RequestTypeEnum.PUSH.value())return enableSSL? HOST_NAME_SSL :HOST_NAME;if(type == RequestTypeEnum.RECEIVE.value())return enableSSL? RECEIVE_HOST_NAME:RECEIVE_HOST_NAME;return null;}
Make a judgment here. If enableSSL is set to false, the request address for sending the message is HOST_NAME. In fact, this enableSSL is set to false by default in the BaseClient class.

public boolean enableSSL = false;
HOST_NAME is the default request address stated in the official document:

public static String HOST_NAME = "http://api.jpush.cn:8800";

public static  String RECEIVE_HOST_NAME = "https://report.jpush.cn:443";  












Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.