JPush API Java Library

Github Source Code

Overview

This is a Java version development package for the JPush REST API. It is provided by the JPush officially and generally supports the latest API features.

Corresponding REST API documentation: REST API - Push, REST API - Report.

This Development Kit Javadoc: API Docs

Version update: Release Page. Download updates here.

Developers are very welcome to submit code and contribute a piece of power. Valid code reviewed will be incorporated into this project.

Installation

Maven Way

Place the following dependencies in your project’s maven pom.xml file.

  1. <dependency>
  2. <groupId>cn.jpush.api</groupId>
  3. <artifactId>jpush-client</artifactId>
  4. <version>3.3.4</version>
  5. </dependency>

Jar Package Mode

Please go to the Release Page to download the corresponding release package

Dependent Package

  • slf4j / log4j (Logger)
  • gson (Google JSON Utils)

Among them, slf4j can work with log frames such as logback, log4j, and commons-logging, and can be configured and used according to your needs.

If you use Maven to build your project, you need to add it to your project pom.xml:

  1. <dependency>
  2. <groupId>cn.jpush.api</groupId>
  3. <artifactId>jiguang-common</artifactId>
  4. <version>1.1.1</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>io.netty</groupId>
  8. <artifactId>netty-all</artifactId>
  9. <version>4.1.6.Final</version>
  10. <scope>compile</scope>
  11. </dependency>
  12. <dependency>
  13. <groupId>com.google.code.gson</groupId>
  14. <artifactId>gson</artifactId>
  15. <version>2.3</version>
  16. </dependency>
  17. <dependency>
  18. <groupId>org.slf4j</groupId>
  19. <artifactId>slf4j-api</artifactId>
  20. <version>1.7.7</version>
  21. </dependency>
  22. <!-- For log4j -->
  23. <dependency>
  24. <groupId>org.slf4j</groupId>
  25. <artifactId>slf4j-log4j12</artifactId>
  26. <version>1.7.7</version>
  27. </dependency>
  28. <dependency>
  29. <groupId>log4j</groupId>
  30. <artifactId>log4j</artifactId>
  31. <version>1.2.17</version>
  32. </dependency>

If you are not using Maven to build the project, the dependencies jar in the project libs/ directory can be copied to your project.

Compile Source Code

If the developer wants to do some extended development based on this project, or want to understand the source code of the project, this chapter can be a reference, otherwise please skip this chapter.

Import this Item

  • You can use git clone https://github.com/jpush/jpush-api-java-client.git jpush-api-src to download the source code
  • If you don’t use git, go to the Release Page to download the source package and unzip it
  • Use eclipse to import and download the source code project. Maven is recommended to facilitate management of dependent packages
  • If you use the method of importing an ordinary project, the project will report and error. Then please check the Build Path, Libraries
  • Dependent jar packages can be found in the libs directory. Please add them to Build Path, Libraries if it is not added
  • Log4j is used as the logging framework by default. Developers can replace logback, commons-logging, and other logging frameworks according to their needs.
  • In rare cases, if the test directory reports an error, please manually add the test dependency jar package mockwebserver-2.0.0.jar, okhttp-2.0.0.jar, okio-1.0.0.jar
  • Developers need to be careful to set the encoding format of this project to UTF-8

Build this Project

You can use the Eclipse class IDE to export jar packages. It is recommended to use maven directly to execute the command:

  1. mvn package

Automated Test

Execute the command in the project directory:

  1. mvn test

Use Samples

If you use NettyHttpClient (new in version 3.2.15), you need to manually call the close method in NettyHttpClient after the response is returned. Otherwise, the process will not exit. Code example:

  1. ...
  2. try {
  3. PushResult result = jpushClient.sendPush(payload);
  4. LOG.info("Got result - " + result);
  5. Thread.sleep(5000);
  6. // 请求结束后,调用 NettyHttpClient 中的 close 方法,否则进程不会退出。
  7. jpushClient.close();
  8. } catch(InterruptedException e) {
  9. e.printStackTrace();
  10. }

After the 3.2.17 release, the user can freely switch between ApacheHttpClient, NettyHttpClient, or NativeHttpClient, if the setHttpClient(IHttpClient client) method was added to the PushClient.

Push Sample

The following fragment comes from the file in the project code: example / cn.jpush.api.examples.PushExample

  1. JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, ClientConfig.getInstance());
  2. // For push, all you need do is to build PushPayload object.
  3. PushPayload payload = buildPushObject_all_all_alert();
  4. try {
  5. PushResult result = jpushClient.sendPush(payload);
  6. LOG.info("Got result - " + result);
  7. } catch (APIConnectionException e) {
  8. // Connection error, should retry later
  9. LOG.error("Connection error, should retry later", e);
  10. } catch (APIRequestException e) {
  11. // Should review the error, and fix the request
  12. LOG.error("Should review the error, and fix the request", e);
  13. LOG.info("HTTP Status: " + e.getStatus());
  14. LOG.info("Error Code: " + e.getErrorCode());
  15. LOG.info("Error Message: " + e.getErrorMessage());
  16. }

The key to pushing is to build a PushPayload object. The following example shows the generic usage for building object.

  • Build push objects quickly: In all platforms and all devices, Notifications with ALERT as its content
  1. public static PushPayload buildPushObject_all_all_alert() {
  2. return PushPayload.alertAll(ALERT);
  3. }
  • Build push objects: In all platforms, the push target with “alias1” as alias and ALERT as notification content.
  1. public static PushPayload buildPushObject_all_alias_alert() {
  2. return PushPayload.newBuilder()
  3. .setPlatform(Platform.all())
  4. .setAudience(Audience.alias("alias1"))
  5. .setNotification(Notification.alert(ALERT))
  6. .build();
  7. }
  • Build push objects: The platform is Android, the target is a device with “tag1” as tag, Android notification ALERT as content, and TITLE as title
  1. public static PushPayload buildPushObject_android_tag_alertWithTitle() {
  2. return PushPayload.newBuilder()
  3. .setPlatform(Platform.android())
  4. .setAudience(Audience.tag("tag1"))
  5. .setNotification(Notification.android(ALERT, TITLE, null))
  6. .build();
  7. }
  • Build push objects: the platform is iOS, the push target is the intersection of “tag1”, “tag_all”, and the push content includes both notifications and messages – ALERT as notification information, 5 as the number of corner signs, “happy” as the notification sound, from = “JPush” as additional Field; the message content is MSG_CONTENT. The notification is in the APNs push channel, and the message is in the JPush application message channel. APNs push environment is “production” (Library defaults to development if not explicitly set)
  1. public static PushPayload buildPushObject_ios_tagAnd_alertWithExtrasAndMessage() {
  2. return PushPayload.newBuilder()
  3. .setPlatform(Platform.ios())
  4. .setAudience(Audience.tag_and("tag1", "tag_all"))
  5. .setNotification(Notification.newBuilder()
  6. .addPlatformNotification(IosNotification.newBuilder()
  7. .setAlert(ALERT)
  8. .setBadge(5)
  9. .setSound("happy")
  10. .addExtra("from", "JPush")
  11. .build())
  12. .build())
  13. .setMessage(Message.content(MSG_CONTENT))
  14. .setOptions(Options.newBuilder()
  15. .setApnsProduction(true)
  16. .build())
  17. .build();
  18. }
  • Build push objects: The platform is Andorid and iOS, the push target is intersection of (the union of “tag1” and “tag2”) (the union of “alias1” and “alias2”), and the push content is - the message with MSG_CONTENT as content and from = JPush as additional fields.
  1. public static PushPayload buildPushObject_ios_audienceMore_messageWithExtras() {
  2. return PushPayload.newBuilder()
  3. .setPlatform(Platform.android_ios())
  4. .setAudience(Audience.newBuilder()
  5. .addAudienceTarget(AudienceTarget.tag("tag1", "tag2"))
  6. .addAudienceTarget(AudienceTarget.alias("alias1", "alias2"))
  7. .build())
  8. .setMessage(Message.newBuilder()
  9. .setMsgContent(MSG_CONTENT)
  10. .addExtra("from", "JPush")
  11. .build())
  12. .build();
  13. }
  • Build push objects: Push content contains SMS information
  1. public static void testSendWithSMS() {
  2. JPushClient jpushClient = new JPushClient(masterSecret, appKey);
  3. try {
  4. SMS sms = SMS.content("Test SMS", 10);
  5. PushResult result = jpushClient.sendAndroidMessageWithAlias("Test SMS", "test sms", sms, "alias1");
  6. LOG.info("Got result - " + result);
  7. } catch (APIConnectionException e) {
  8. LOG.error("Connection error. Should retry later. ", e);
  9. } catch (APIRequestException e) {
  10. LOG.error("Error response from JPush server. Should review and fix it. ", e);
  11. LOG.info("HTTP Status: " + e.getStatus());
  12. LOG.info("Error Code: " + e.getErrorCode());
  13. LOG.info("Error Message: " + e.getErrorMessage());
  14. }
  15. }

Statistics Acquisition Sample

The following fragment comes from the file in the project code: example / cn.jpush.api.examples.ReportsExample

  1. JPushClient jpushClient = new JPushClient(masterSecret, appKey);
  2. try {
  3. ReceivedsResult result = jpushClient.getReportReceiveds("1942377665");
  4. LOG.debug("Got result - " + result);
  5. } catch (APIConnectionException e) {
  6. // Connection error, should retry later
  7. LOG.error("Connection error, should retry later", e);
  8. } catch (APIRequestException e) {
  9. // Should review the error, and fix the request
  10. LOG.error("Should review the error, and fix the request", e);
  11. LOG.info("HTTP Status: " + e.getStatus());
  12. LOG.info("Error Code: " + e.getErrorCode());
  13. LOG.info("Error Message: " + e.getErrorMessage());
  14. }

Tag/Alias Sample

The following fragment comes from the file in the project code: example /cn.jpush.api.examples.DeviceExample

  • Get Tag Alias
  1. try {
  2. TagAliasResult result = jpushClient.getDeviceTagAlias(REGISTRATION_ID1);
  3. LOG.info(result.alias);
  4. LOG.info(result.tags.toString());
  5. } catch (APIConnectionException e) {
  6. LOG.error("Connection error. Should retry later. ", e);
  7. } catch (APIRequestException e) {
  8. LOG.error("Error response from JPush server. Should review and fix it. ", e);
  9. LOG.info("HTTP Status: " + e.getStatus());
  10. LOG.info("Error Code: " + e.getErrorCode());
  11. LOG.info("Error Message: " + e.getErrorMessage());
  12. }
  • Bind Phone Number
  1. try {
  2. DefaultResult result = jpushClient.bindMobile(REGISTRATION_ID1, "13000000000");
  3. LOG.info("Got result " + result);
  4. } catch (APIConnectionException e) {
  5. LOG.error("Connection error. Should retry later. ", e);
  6. } catch (APIRequestException e) {
  7. LOG.error("Error response from JPush server. Should review and fix it. ", e);
  8. LOG.info("HTTP Status: " + e.getStatus());
  9. LOG.info("Error Code: " + e.getErrorCode());
  10. LOG.info("Error Message: " + e.getErrorMessage());
  11. }

Schedule Sample

The following fragment comes from the file in the project code: example / cn.jpush.api.examples.ScheduleExample

  1. JPushClient jpushClient = new JPushClient(masterSecret, appKey);
  2. String name = "test_schedule_example";
  3. String time = "2016-07-30 12:30:25";
  4. PushPayload push = PushPayload.alertAll("test schedule example.");
  5. try {
  6. ScheduleResult result = jpushClient.createSingleSchedule(name, time, push);
  7. LOG.info("schedule result is " + result);
  8. } catch (APIConnectionException e) {
  9. LOG.error("Connection error. Should retry later. ", e);
  10. } catch (APIRequestException e) {
  11. LOG.error("Error response from JPush server. Should review and fix it. ", e);
  12. LOG.info("HTTP Status: " + e.getStatus());
  13. LOG.info("Error Code: " + e.getErrorCode());
  14. LOG.info("Error Message: " + e.getErrorMessage());
  15. }

Sample of Custom Client

The fragment comes from the file in the project code: example /cn.jpush.api.examples.ClientExample

  • The configured SSLVersion indicates that at least the supported protocol version is specified, and other multiple protocol versions may also be supported. The list of supported protocol versions depends on the JRE and the operating environment.
  1. public static void testCustomClient() {
  2. ClientConfig config = ClientConfig.getInstance();
  3. config.setMaxRetryTimes(5);
  4. config.setConnectionTimeout(10 * 1000); // 10 seconds
  5. config.setSSLVersion("TLSv1.1"); // JPush server supports SSLv3, TLSv1, TLSv1.1, TLSv1.2
  6. JPushClient jPushClient = new JPushClient(masterSecret, appKey, null, config);
  7. }
  8. public static void testCustomPushClient() {
  9. ClientConfig config = ClientConfig.getInstance();
  10. config.setApnsProduction(false); // development env
  11. config.setTimeToLive(60 * 60 * 24); // one day
  12. // config.setGlobalPushSetting(false, 60 * 60 * 24); // development env, one day
  13. JPushClient jPushClient = new JPushClient(masterSecret, appKey, null, config); // JPush client
  14. // PushClient pushClient = new PushClient(masterSecret, appKey, null, config); // push client only
  15. }

Weblogic Uses the Java SDK

Some things that needs to pay attention to when using jpush-api-java-client by Weblogic.

Precautions

This document is based on weblogic 10.3.6 version. For version 12, please configure the path accordingly.

In rare cases, the certificate will have a version upgrade, so be sure to verify that the fingerprints of current and the official certificate are the same.

Settings of Weblogic console

  • [HostName Authentication] Set to None, otherwise, weblogic.security.SSL.HostnameVerifier is used for host name verification, and hostname authentication will fail.
    • Configuration path Weblogic Console> Server Settings> SSL> Advanced> Host Name Verification
  • Select [Use JSSE SSL], because Weblogic’s default encryption algorithm is different from the encryption algorithm in Java standard
    • Configuration path Weblogic Console> Server Settings> SSL> Advanced> Using JSSE SSL

Certificate Configuration

  • Check the location of the Trust Key Store used by Weblogic
    • The default file used is the jre\lib\security\cacerts file in the JRE directory
    • Some developers may change to a custom Trust Key Store
  • Check if the corresponding truststore contains the root certificate of Geo Trust or secondary certificate of Geo Trust SSL
    • Example: keytool -list -keystore cacerts
    • This process requires the password of the truststore (default changeit)
    • If any of these two certificates is contained, calling the JPush interface can be invoked through
  • If the truststore does not contain the above certificate, you need to import the public key to the corresponding truststore
    • Open jpush.cn and export the public key (can be either Geo Trust root certificate, Geo Trust SSL or *.jpush.cn, please search in Baidu for specific exporting method)
    • Import the exported public key certificate to the corresponding trust store in step 1
    • Example: keytool -import -alias geotrustssl -keystore cacerts -file GeoTrustSSL.cer
    • This process requires the password of the truststore (default changeit)

Comparison of Certificates

  • Execute the keytool -list -keystore mykey.jks command to list all the public keys in the truststore and observe the fingerprint of the corresponding certificate.
  • Check the official website certificate and observe the fingerprint of the corresponding certificate
  • Compare whether two fingerprints are the same, as shown in the figure below