├── libs ├── gson-2.2.4.jar ├── log4j-1.2.17.jar ├── slf4j-api-1.7.7.jar ├── jsms-client-1.2.2.jar ├── slf4j-log4j12-1.7.7.jar └── jiguang-common-1.0.8.jar ├── src ├── test │ └── java │ │ └── cn │ │ └── jsms │ │ └── api │ │ ├── FastTests.java │ │ ├── SlowTests.java │ │ ├── BaseTest.java │ │ └── sms │ │ └── SMSClientTest.java └── main │ └── java │ └── cn │ └── jsms │ └── api │ ├── common │ ├── model │ │ ├── IModel.java │ │ ├── BatchSMSResult.java │ │ ├── RecipientPayload.java │ │ ├── BatchSMSPayload.java │ │ └── SMSPayload.java │ ├── JSMSConfig.java │ └── SMSClient.java │ ├── SendSMSResult.java │ ├── sign │ ├── SignResult.java │ ├── SignInfoResult.java │ ├── DefaultSignPayload.java │ └── SignPayload.java │ ├── ValidSMSResult.java │ ├── template │ ├── SendTempSMSResult.java │ ├── TempSMSResult.java │ └── TemplatePayload.java │ ├── account │ ├── AppBalanceResult.java │ └── AccountBalanceResult.java │ ├── schedule │ └── model │ │ ├── ScheduleResult.java │ │ ├── ScheduleSMSResult.java │ │ └── ScheduleSMSPayload.java │ └── JSMSClient.java ├── .gitignore ├── example └── main │ └── java │ ├── log4j.properties │ └── cn │ └── jsms │ └── api │ └── JSMSExample.java ├── .project ├── LICENSE ├── .github └── workflows │ └── maven.yml ├── .classpath ├── README.md └── pom.xml /libs/gson-2.2.4.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jpush/jsms-api-java-client/HEAD/libs/gson-2.2.4.jar -------------------------------------------------------------------------------- /libs/log4j-1.2.17.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jpush/jsms-api-java-client/HEAD/libs/log4j-1.2.17.jar -------------------------------------------------------------------------------- /libs/slf4j-api-1.7.7.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jpush/jsms-api-java-client/HEAD/libs/slf4j-api-1.7.7.jar -------------------------------------------------------------------------------- /src/test/java/cn/jsms/api/FastTests.java: -------------------------------------------------------------------------------- 1 | package cn.jsms.api; 2 | 3 | public interface FastTests { 4 | } 5 | -------------------------------------------------------------------------------- /src/test/java/cn/jsms/api/SlowTests.java: -------------------------------------------------------------------------------- 1 | package cn.jsms.api; 2 | 3 | public interface SlowTests { 4 | } 5 | -------------------------------------------------------------------------------- /libs/jsms-client-1.2.2.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jpush/jsms-api-java-client/HEAD/libs/jsms-client-1.2.2.jar -------------------------------------------------------------------------------- /libs/slf4j-log4j12-1.7.7.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jpush/jsms-api-java-client/HEAD/libs/slf4j-log4j12-1.7.7.jar -------------------------------------------------------------------------------- /libs/jiguang-common-1.0.8.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jpush/jsms-api-java-client/HEAD/libs/jiguang-common-1.0.8.jar -------------------------------------------------------------------------------- /src/main/java/cn/jsms/api/common/model/IModel.java: -------------------------------------------------------------------------------- 1 | package cn.jsms.api.common.model; 2 | 3 | import com.google.gson.JsonElement; 4 | 5 | public interface IModel { 6 | 7 | public JsonElement toJSON(); 8 | 9 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | *.iml 3 | *.idea/ 4 | .DS_Store 5 | 6 | 7 | # Mobile Tools for Java (J2ME) 8 | .mtj.tmp/ 9 | 10 | # Package Files # 11 | *.war 12 | *.ear 13 | *.settings/ 14 | target/ 15 | 16 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 17 | hs_err_pid* 18 | -------------------------------------------------------------------------------- /src/main/java/cn/jsms/api/SendSMSResult.java: -------------------------------------------------------------------------------- 1 | package cn.jsms.api; 2 | 3 | import com.google.gson.annotations.Expose; 4 | 5 | import cn.jiguang.common.resp.BaseResult; 6 | 7 | public class SendSMSResult extends BaseResult { 8 | 9 | @Expose String msg_id; 10 | 11 | public String getMessageId() { 12 | return msg_id; 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/cn/jsms/api/sign/SignResult.java: -------------------------------------------------------------------------------- 1 | package cn.jsms.api.sign; 2 | 3 | import cn.jiguang.common.resp.BaseResult; 4 | import com.google.gson.annotations.Expose; 5 | 6 | public class SignResult extends BaseResult { 7 | @Expose 8 | int sign_id; 9 | 10 | public int getSign_id() { 11 | return sign_id; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/cn/jsms/api/ValidSMSResult.java: -------------------------------------------------------------------------------- 1 | package cn.jsms.api; 2 | 3 | import com.google.gson.annotations.Expose; 4 | 5 | import cn.jiguang.common.resp.BaseResult; 6 | 7 | 8 | public class ValidSMSResult extends BaseResult { 9 | 10 | @Expose Boolean is_valid; 11 | 12 | public Boolean getIsValid() { 13 | return is_valid; 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /example/main/java/log4j.properties: -------------------------------------------------------------------------------- 1 | log4j.rootLogger=DEBUG,CONSOLE 2 | 3 | log4j.logger.org.eclipse.jetty=INFO 4 | 5 | log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender 6 | log4j.appender.CONSOLE.Target=System.out 7 | log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout 8 | log4j.appender.CONSOLE.layout.ConversionPattern=%d{yy/MM/dd HH:mm:ss} %p %c{2}: %m%n 9 | -------------------------------------------------------------------------------- /src/main/java/cn/jsms/api/template/SendTempSMSResult.java: -------------------------------------------------------------------------------- 1 | package cn.jsms.api.template; 2 | 3 | import cn.jiguang.common.resp.BaseResult; 4 | import com.google.gson.annotations.Expose; 5 | 6 | public class SendTempSMSResult extends BaseResult { 7 | 8 | @Expose int temp_id; 9 | 10 | public int getTempId() { 11 | return temp_id; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/cn/jsms/api/account/AppBalanceResult.java: -------------------------------------------------------------------------------- 1 | package cn.jsms.api.account; 2 | 3 | import cn.jiguang.common.resp.BaseResult; 4 | import com.google.gson.annotations.Expose; 5 | 6 | public class AppBalanceResult extends BaseResult { 7 | 8 | @Expose int app_balance; 9 | 10 | public int getAppBalance() { 11 | return app_balance; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/cn/jsms/api/account/AccountBalanceResult.java: -------------------------------------------------------------------------------- 1 | package cn.jsms.api.account; 2 | 3 | import cn.jiguang.common.resp.BaseResult; 4 | import com.google.gson.annotations.Expose; 5 | 6 | public class AccountBalanceResult extends BaseResult { 7 | @Expose int dev_balance; 8 | 9 | public int getDevBalance() { 10 | return dev_balance; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/cn/jsms/api/schedule/model/ScheduleResult.java: -------------------------------------------------------------------------------- 1 | package cn.jsms.api.schedule.model; 2 | 3 | import cn.jiguang.common.resp.BaseResult; 4 | import com.google.gson.annotations.Expose; 5 | 6 | public class ScheduleResult extends BaseResult { 7 | 8 | @Expose String schedule_id; 9 | 10 | public String getScheduleId() { 11 | return schedule_id; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/test/java/cn/jsms/api/BaseTest.java: -------------------------------------------------------------------------------- 1 | package cn.jsms.api; 2 | 3 | public class BaseTest { 4 | 5 | protected static final String APP_KEY ="d4ee2375846bc30fa51334f5"; 6 | protected static final String MASTER_SECRET = "cfb11ca45888cdd6388483f5"; 7 | 8 | protected static final String DEV_KEY = "8885227f9e44358a59aa0880"; 9 | protected static final String DEV_SECRET = "281399a95fa3be40645f0558"; 10 | } 11 | -------------------------------------------------------------------------------- /.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | jsms-client 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.m2e.core.maven2Builder 15 | 16 | 17 | 18 | 19 | 20 | org.eclipse.jdt.core.javanature 21 | org.eclipse.m2e.core.maven2Nature 22 | 23 | 24 | -------------------------------------------------------------------------------- /src/main/java/cn/jsms/api/sign/SignInfoResult.java: -------------------------------------------------------------------------------- 1 | package cn.jsms.api.sign; 2 | 3 | import cn.jiguang.common.resp.BaseResult; 4 | import com.google.gson.annotations.Expose; 5 | 6 | public class SignInfoResult extends BaseResult { 7 | @Expose 8 | int sign_id; 9 | @Expose 10 | String sign; 11 | @Expose 12 | int status; 13 | @Expose 14 | int is_default; 15 | 16 | public int getSign_id() { 17 | return sign_id; 18 | } 19 | 20 | public String getSign() { 21 | return sign; 22 | } 23 | 24 | public int getStatus() { 25 | return status; 26 | } 27 | 28 | public int getIs_default() { 29 | return is_default; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/cn/jsms/api/template/TempSMSResult.java: -------------------------------------------------------------------------------- 1 | package cn.jsms.api.template; 2 | 3 | import cn.jiguang.common.resp.BaseResult; 4 | import com.google.gson.annotations.Expose; 5 | 6 | public class TempSMSResult extends BaseResult { 7 | 8 | @Expose int temp_id; 9 | @Expose String template; 10 | @Expose int type; 11 | @Expose int ttl; 12 | @Expose String remark; 13 | @Expose int status; 14 | 15 | public int getTempId() { 16 | return temp_id; 17 | } 18 | 19 | public String getTemplate() { 20 | return template; 21 | } 22 | 23 | public int getType() { 24 | return type; 25 | } 26 | 27 | public int getTtl() { 28 | return ttl; 29 | } 30 | 31 | public String getRemark() { 32 | return remark; 33 | } 34 | 35 | public int getStatus() { 36 | return status; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 极光 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/main/java/cn/jsms/api/schedule/model/ScheduleSMSResult.java: -------------------------------------------------------------------------------- 1 | package cn.jsms.api.schedule.model; 2 | 3 | import cn.jiguang.common.resp.BaseResult; 4 | import com.google.gson.JsonObject; 5 | import com.google.gson.annotations.Expose; 6 | 7 | import java.util.List; 8 | 9 | public class ScheduleSMSResult extends BaseResult { 10 | 11 | @Expose String schedule_id; 12 | @Expose String send_time; 13 | @Expose int temp_id; 14 | @Expose List recipients; 15 | 16 | public String getScheduleId() { 17 | return schedule_id; 18 | } 19 | 20 | public String getSendTime() { 21 | return send_time; 22 | } 23 | 24 | public int getTempId() { 25 | return temp_id; 26 | } 27 | 28 | public List getRecipients() { 29 | return recipients; 30 | } 31 | 32 | public static class Recipient { 33 | @Expose String msg_id; 34 | @Expose String mobile; 35 | @Expose JsonObject temp_para; 36 | 37 | public String getMsgId() { 38 | return msg_id; 39 | } 40 | 41 | public String getMobile() { 42 | return mobile; 43 | } 44 | 45 | public JsonObject getTempPara() { 46 | return temp_para; 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /.github/workflows/maven.yml: -------------------------------------------------------------------------------- 1 | name: Publish package to the Maven Central Repository 2 | on: 3 | release: 4 | types: [published] 5 | 6 | jobs: 7 | publish: 8 | runs-on: ubuntu-latest 9 | 10 | steps: 11 | - uses: actions/checkout@v2 12 | - name: Set up JDK 1.8 13 | uses: actions/setup-java@v1 14 | with: 15 | java-version: 1.8 16 | 17 | - name: Build with Maven 18 | run: mvn -B clean package -Dmaven.test.skip 19 | 20 | - name: Set up Apache Maven Central 21 | uses: actions/setup-java@v1 22 | with: # running setup-java again overwrites the settings.xml 23 | java-version: 1.8 24 | server-id: ossrh # Value of the distributionManagement/repository/id field of the pom.xml 25 | server-username: MAVEN_USERNAME # env variable for username in deploy 26 | server-password: MAVEN_PASSWORD # env variable for token in deploy 27 | gpg-private-key: ${{ secrets.MAVEN_GPG_PRIVATE_KEY }} # Value of the GPG private key to import 28 | gpg-passphrase: MAVEN_GPG_PASSPHRASE # env variable for GPG private key passphrase 29 | 30 | - name: Publish to Apache Maven Central 31 | run: mvn deploy -Dmaven.test.skip 32 | env: 33 | MAVEN_USERNAME: ${{ secrets.OSSRH_USERNAME }} 34 | MAVEN_PASSWORD: ${{ secrets.OSSRH_TOKEN }} 35 | MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }} -------------------------------------------------------------------------------- /.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /src/main/java/cn/jsms/api/common/model/BatchSMSResult.java: -------------------------------------------------------------------------------- 1 | package cn.jsms.api.common.model; 2 | 3 | import cn.jiguang.common.resp.BaseResult; 4 | import com.google.gson.JsonElement; 5 | import com.google.gson.JsonObject; 6 | import com.google.gson.annotations.Expose; 7 | 8 | import java.util.List; 9 | 10 | public class BatchSMSResult extends BaseResult { 11 | 12 | @Expose String schedule_id; 13 | @Expose int success_count; 14 | @Expose int failure_count; 15 | @Expose List failure_recipients; 16 | 17 | public String getScheduleId() { 18 | return schedule_id; 19 | } 20 | 21 | public int getSuccessCount() { 22 | return success_count; 23 | } 24 | 25 | public int getFailureCount() { 26 | return failure_count; 27 | } 28 | 29 | public List getFailureRecipients() { 30 | return failure_recipients; 31 | } 32 | 33 | public static class FailureRecipients { 34 | 35 | @Expose String error_code; 36 | @Expose String error_message; 37 | @Expose String mobile; 38 | @Expose JsonObject temp_para; 39 | 40 | public String getErrorCode() { 41 | return error_code; 42 | } 43 | 44 | public String getErrorMessage() { 45 | return error_message; 46 | } 47 | 48 | public String getMobile() { 49 | return mobile; 50 | } 51 | 52 | public JsonObject getTempPara() { 53 | return temp_para; 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/cn/jsms/api/sign/DefaultSignPayload.java: -------------------------------------------------------------------------------- 1 | package cn.jsms.api.sign; 2 | 3 | import cn.jsms.api.common.model.IModel; 4 | import cn.jsms.api.template.TemplatePayload; 5 | import com.google.gson.Gson; 6 | import com.google.gson.JsonElement; 7 | import com.google.gson.JsonObject; 8 | 9 | public class DefaultSignPayload implements IModel { 10 | 11 | private static String ID = "id"; 12 | private static String NAME = "name"; 13 | private int id; 14 | private String name; 15 | private static Gson gson = new Gson(); 16 | 17 | private DefaultSignPayload(Builder builder) { 18 | id = builder.id; 19 | name = builder.name; 20 | } 21 | 22 | 23 | public static final class Builder { 24 | private int id; 25 | private String name; 26 | 27 | public Builder() { 28 | } 29 | 30 | public Builder id(int val) { 31 | id = val; 32 | return this; 33 | } 34 | 35 | public Builder name(String val) { 36 | name = val; 37 | return this; 38 | } 39 | 40 | public DefaultSignPayload build() { 41 | return new DefaultSignPayload(this); 42 | } 43 | } 44 | 45 | public static DefaultSignPayload.Builder newBuilder() { 46 | return new DefaultSignPayload.Builder(); 47 | } 48 | 49 | public JsonElement toJSON() { 50 | JsonObject json = new JsonObject(); 51 | 52 | if (id > 0) { 53 | json.addProperty(ID, id); 54 | } 55 | 56 | if (name != null) { 57 | json.addProperty(NAME, name); 58 | } 59 | 60 | return json; 61 | } 62 | 63 | @Override 64 | public String toString() { 65 | return gson.toJson(toJSON()); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # JSMS API JAVA CLIENT 2 | 3 | ### 概述 4 | 这是短信 Rest API 的 Java 版本封装开发包,是由极光推送官方提供的,一般支持最新的 API功能。 5 | 6 | 对应的 Rest API 文档:https://docs.jiguang.cn/jsms/server/rest_api_summary/ 7 | 8 | ## 安装 9 | 10 | ### maven 方式 11 | 将下边的依赖条件放到你项目的 maven pom.xml 文件里。 12 | > 其中 slf4j 可以与 logback, log4j, commons-logging 等日志框架一起工作,可根据你的需要配置使用。 13 | 14 | 其中 LATEST_VERSION 的值可在 [release 页面](https://github.com/jpush/jsms-api-java-client/releases/latest) 获取 15 | 16 | ```Java 17 | 18 |    cn.jpush.api 19 | jsms-client 20 | LATEST_VERSION 21 | 22 | 23 | com.google.code.gson 24 | gson 25 | 2.3 26 | 27 | 28 | org.slf4j 29 | slf4j-api 30 | 1.7.7 31 | 32 | 33 | cn.jpush.api 34 | jiguang-common 35 | 1.0.8 36 | 37 | 38 | 39 | org.slf4j 40 | slf4j-log4j12 41 | 1.7.7 42 | 43 | 44 | log4j 45 | log4j 46 | 1.2.17 47 | 48 | ``` 49 | 50 | ### jar 包方式 51 | * [slf4j](http://www.slf4j.org/) / log4j (Logger) 52 | * [gson](https://code.google.com/p/google-gson/) (Google JSON Utils) 53 | * [jiguang-common-client](https://github.com/jpush/jiguang-java-client-common) 54 | * [jsms-client](https://github.com/jpush/jsms-api-java-client/releases/latest) 55 | 56 | [项目 libs/ 目录](https://github.com/jpush/jsms-api-java-client/tree/master/libs)下可以找到 slf4j 及 gson jar 包 可复制到你的项目里去。 57 | -------------------------------------------------------------------------------- /src/main/java/cn/jsms/api/common/JSMSConfig.java: -------------------------------------------------------------------------------- 1 | package cn.jsms.api.common; 2 | 3 | import cn.jiguang.common.ClientConfig; 4 | 5 | public class JSMSConfig { 6 | 7 | private static ClientConfig clientConfig = ClientConfig.getInstance(); 8 | 9 | private static JSMSConfig instance = new JSMSConfig(); 10 | 11 | public final static String API_HOST_NAME = "sms.api.host.name"; 12 | 13 | public final static String CODE_PATH = "sms.code.path"; 14 | 15 | public final static String VALID_PATH = "sms.valid.path"; 16 | 17 | public final static String VOICE_CODE_PATH = "sms.voice.code.path"; 18 | 19 | public final static String SHORT_MESSAGE_PATH = "sms.message.path"; 20 | 21 | public final static String TEMPlATE_MESSAGE_PATH = "sms.template.path"; 22 | 23 | public final static String SIGN_PATH = "sms.sign.path"; 24 | public final static String SIGN_DEFAULT_PATH = "sms.sign.default.path"; 25 | 26 | 27 | public final static String SCHEDULE_PATH = "sms.schedule.path"; 28 | 29 | public final static String ACCOUNT_PATH = "sms.account.path"; 30 | 31 | public static final String MAX_RETRY_TIMES = ClientConfig.MAX_RETRY_TIMES; 32 | 33 | public static final String SEND_VERSION = "send.version"; 34 | 35 | public JSMSConfig() { 36 | clientConfig.put(API_HOST_NAME, "https://api.sms.jpush.cn"); 37 | clientConfig.put(CODE_PATH, "/v1/codes"); 38 | clientConfig.put(VALID_PATH, "/valid"); 39 | clientConfig.put(VOICE_CODE_PATH, "/v1/voice_codes"); 40 | clientConfig.put(SHORT_MESSAGE_PATH, "/v1/messages"); 41 | clientConfig.put(TEMPlATE_MESSAGE_PATH, "/v1/templates"); 42 | clientConfig.put(SIGN_PATH,"/v1/sign"); 43 | clientConfig.put(SIGN_DEFAULT_PATH,"/v1/setDefaultSign"); 44 | clientConfig.put(SCHEDULE_PATH, "/v1/schedule"); 45 | clientConfig.put(ACCOUNT_PATH, "/v1/accounts"); 46 | clientConfig.put(MAX_RETRY_TIMES, 3); 47 | clientConfig.put(SEND_VERSION, 1); 48 | } 49 | 50 | public static JSMSConfig getInstance() { 51 | return instance; 52 | } 53 | 54 | public ClientConfig getClientConfig() { 55 | return clientConfig; 56 | } 57 | 58 | public Object get(String key) { 59 | return clientConfig.get(key); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/cn/jsms/api/common/model/RecipientPayload.java: -------------------------------------------------------------------------------- 1 | package cn.jsms.api.common.model; 2 | 3 | import cn.jiguang.common.utils.Preconditions; 4 | import cn.jiguang.common.utils.StringUtils; 5 | import com.google.gson.*; 6 | 7 | import java.util.HashMap; 8 | import java.util.Map; 9 | 10 | public class RecipientPayload implements IModel { 11 | 12 | private final static String MOBILE = "mobile"; 13 | private final static String TEMP_PARA = "temp_para"; 14 | 15 | private String mobile; 16 | private Map temp_para; 17 | private Gson gson = new Gson(); 18 | 19 | public RecipientPayload(String mobile, Map tempPara) { 20 | this.mobile = mobile; 21 | this.temp_para = tempPara; 22 | } 23 | 24 | public static Builder newBuilder() { 25 | return new Builder(); 26 | } 27 | 28 | public static class Builder { 29 | private String mobile; 30 | private Map tempPara; 31 | 32 | public Builder setMobile(String mobileNumber) { 33 | this.mobile = mobileNumber.trim(); 34 | return this; 35 | } 36 | 37 | public Builder setTempPara(Map temp_para) { 38 | Preconditions.checkArgument(! (null == temp_para), "temp_para should not be null."); 39 | if (null == tempPara) { 40 | tempPara = new HashMap(); 41 | } 42 | for (String key : temp_para.keySet()) { 43 | tempPara.put(key, temp_para.get(key)); 44 | } 45 | return this; 46 | } 47 | 48 | public Builder addTempPara(String key, String value) { 49 | Preconditions.checkArgument(! (null == key || null == value), "Key/Value should not be null."); 50 | if (null == tempPara) { 51 | tempPara = new HashMap(); 52 | } 53 | tempPara.put(key, value); 54 | return this; 55 | } 56 | 57 | public RecipientPayload build() { 58 | Preconditions.checkArgument(null != mobile, "mobile number should not be null"); 59 | Preconditions.checkArgument(StringUtils.isNotEmpty(mobile), "mobile number should not be empty"); 60 | 61 | return new RecipientPayload(mobile, tempPara); 62 | } 63 | } 64 | 65 | @Override 66 | public JsonElement toJSON() { 67 | JsonObject jsonObject = new JsonObject(); 68 | if (null != mobile) { 69 | jsonObject.addProperty(MOBILE, mobile); 70 | } 71 | 72 | JsonObject tempJson = null; 73 | if (null != temp_para) { 74 | tempJson = new JsonObject(); 75 | for (String key : temp_para.keySet()) { 76 | if (temp_para.get(key) != null) { 77 | tempJson.add(key, new JsonPrimitive(temp_para.get(key))); 78 | } else { 79 | tempJson.add(key, JsonNull.INSTANCE); 80 | } 81 | } 82 | } 83 | 84 | if (null != tempJson) { 85 | jsonObject.add(TEMP_PARA, tempJson); 86 | } 87 | return jsonObject; 88 | } 89 | 90 | @Override 91 | public String toString() { 92 | return gson.toJson(toJSON()); 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/main/java/cn/jsms/api/template/TemplatePayload.java: -------------------------------------------------------------------------------- 1 | package cn.jsms.api.template; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | import cn.jsms.api.common.model.IModel; 7 | import com.google.gson.*; 8 | 9 | import cn.jiguang.common.utils.Preconditions; 10 | import cn.jiguang.common.utils.StringUtils; 11 | 12 | 13 | public class TemplatePayload implements IModel { 14 | 15 | private static String TEMPLATE = "template"; 16 | private static String TEMP_ID = "temp_id"; 17 | private static String TTL = "ttl"; 18 | private static String TYPE = "type"; 19 | private static String REMARK = "remark"; 20 | 21 | private int temp_id = -1; 22 | private String template; 23 | private int type; 24 | // Time to live parameter, the unit is second. 25 | private int ttl; 26 | private String remark; 27 | 28 | private static Gson gson = new Gson(); 29 | 30 | private TemplatePayload(int temp_id, String template, int type, int ttl, String remark) { 31 | this.temp_id = temp_id; 32 | this.template = template; 33 | this.type = type; 34 | this.ttl = ttl; 35 | this.remark = remark; 36 | } 37 | 38 | public static Builder newBuilder() { 39 | return new Builder(); 40 | } 41 | 42 | public static class Builder { 43 | private int tempId; 44 | private String template; 45 | private int type; 46 | private int ttl; 47 | private String remark; 48 | 49 | public Builder setTempId(int tempId) { 50 | this.tempId = tempId; 51 | return this; 52 | } 53 | 54 | public Builder setTemplate(String template) { 55 | this.template = template; 56 | return this; 57 | } 58 | 59 | public Builder setTTL(int ttl) { 60 | this.ttl = ttl; 61 | return this; 62 | } 63 | 64 | public Builder setType(int type) { 65 | this.type = type; 66 | return this; 67 | } 68 | 69 | public Builder setRemark(String remark) { 70 | this.remark = remark; 71 | return this; 72 | } 73 | 74 | public TemplatePayload build() { 75 | Preconditions.checkArgument(ttl >= 0, "ttl should not less 0"); 76 | Preconditions.checkArgument(type > 0, "type should be 1, or 2 or 3"); 77 | 78 | return new TemplatePayload(tempId, template, type, ttl, remark); 79 | } 80 | } 81 | 82 | public JsonElement toJSON() { 83 | JsonObject json = new JsonObject(); 84 | 85 | if (temp_id != -1) { 86 | json.addProperty(TEMP_ID, temp_id); 87 | } 88 | 89 | if (template != null) { 90 | json.addProperty(TEMPLATE, template); 91 | } 92 | 93 | if (type > 0) { 94 | json.addProperty(TYPE, type); 95 | } 96 | 97 | if (ttl > 0) { 98 | json.addProperty(TTL, ttl); 99 | } 100 | 101 | if (remark != null) { 102 | json.addProperty(REMARK, remark); 103 | } 104 | return json; 105 | } 106 | 107 | @Override 108 | public String toString() { 109 | return gson.toJson(toJSON()); 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /src/main/java/cn/jsms/api/common/model/BatchSMSPayload.java: -------------------------------------------------------------------------------- 1 | package cn.jsms.api.common.model; 2 | 3 | import cn.jiguang.common.utils.Preconditions; 4 | import com.google.gson.Gson; 5 | import com.google.gson.JsonArray; 6 | import com.google.gson.JsonElement; 7 | import com.google.gson.JsonObject; 8 | 9 | public class BatchSMSPayload implements IModel { 10 | 11 | private static String SIGN_ID = "sign_id"; 12 | private static String TEMP_ID = "temp_id"; 13 | private static String TAG = "tag"; 14 | private static String RECIPIENTS = "recipients"; 15 | 16 | private int sign_id; 17 | private int temp_id; 18 | private String tag; 19 | private static Gson gson = new Gson(); 20 | private JsonArray recipients; 21 | 22 | private BatchSMSPayload(int signId, String tag, int tempId, JsonArray recipients) { 23 | this.sign_id = signId; 24 | this.temp_id = tempId; 25 | this.tag = tag; 26 | this.recipients = recipients; 27 | } 28 | 29 | public static Builder newBuilder() { 30 | return new Builder(); 31 | } 32 | 33 | public static class Builder { 34 | private int sign_id; 35 | private int temp_id; 36 | private String tag; 37 | private JsonArray recipients = new JsonArray(); 38 | 39 | public Builder setSignId(int signId) { 40 | this.sign_id = signId; 41 | return this; 42 | } 43 | 44 | public Builder setTempId(int tempId) { 45 | this.temp_id = tempId; 46 | return this; 47 | } 48 | 49 | public Builder setTag(String tag) { 50 | this.tag = tag; 51 | return this; 52 | } 53 | 54 | public Builder setRecipients(RecipientPayload...recipients) { 55 | if (recipients == null) { 56 | return this; 57 | } 58 | 59 | for (RecipientPayload recipientPayload : recipients) { 60 | this.recipients.add(recipientPayload.toJSON()); 61 | } 62 | return this; 63 | } 64 | 65 | public Builder addRecipient(RecipientPayload recipientPayload) { 66 | Preconditions.checkArgument(null != recipientPayload, "RecipientPayload should not be null"); 67 | this.recipients.add(recipientPayload.toJSON()); 68 | return this; 69 | } 70 | 71 | public BatchSMSPayload build() { 72 | Preconditions.checkArgument(temp_id >= 0, "temp id should not less 0"); 73 | return new BatchSMSPayload(sign_id, tag, temp_id, recipients); 74 | } 75 | } 76 | 77 | @Override 78 | public JsonElement toJSON() { 79 | JsonObject jsonObject = new JsonObject(); 80 | 81 | if (sign_id > 0) { 82 | jsonObject.addProperty(SIGN_ID, sign_id); 83 | } 84 | 85 | if (temp_id > 0) { 86 | jsonObject.addProperty(TEMP_ID, temp_id); 87 | } 88 | 89 | if (null != tag) { 90 | jsonObject.addProperty(TAG, tag); 91 | } 92 | 93 | if (null != recipients && recipients.size() > 0) { 94 | jsonObject.add(RECIPIENTS, recipients); 95 | } 96 | return jsonObject; 97 | } 98 | 99 | @Override 100 | public String toString() { 101 | return gson.toJson(toJSON()); 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /src/main/java/cn/jsms/api/sign/SignPayload.java: -------------------------------------------------------------------------------- 1 | package cn.jsms.api.sign; 2 | 3 | import cn.jiguang.common.utils.Preconditions; 4 | import cn.jiguang.common.utils.StringUtils; 5 | import cn.jsms.api.common.model.IModel; 6 | import cn.jsms.api.template.TemplatePayload; 7 | import com.google.gson.Gson; 8 | import com.google.gson.JsonElement; 9 | import com.google.gson.JsonObject; 10 | 11 | import java.io.File; 12 | 13 | public class SignPayload implements IModel { 14 | 15 | private static String SIGN = "sign"; 16 | private static String IMAGES = "images"; 17 | private static String TYPE = "type"; 18 | private static String REMARK = "remark"; 19 | 20 | private String sign; 21 | private File[] images; 22 | private String remark; 23 | private Integer type; 24 | 25 | private static Gson gson = new Gson(); 26 | 27 | public SignPayload(String sign, File[] images, String remark, Integer type) { 28 | this.sign = sign; 29 | this.images = images; 30 | this.remark = remark; 31 | this.type = type; 32 | } 33 | 34 | private SignPayload(Builder builder) { 35 | sign = builder.sign; 36 | images = builder.images; 37 | remark = builder.remark; 38 | type = builder.type; 39 | } 40 | public static SignPayload.Builder newBuilder() { 41 | return new SignPayload.Builder(); 42 | } 43 | public static final class Builder { 44 | private String sign; 45 | private File[] images; 46 | private String remark; 47 | private Integer type; 48 | 49 | public Builder() { 50 | } 51 | 52 | public Builder sign(String val) { 53 | sign = val; 54 | return this; 55 | } 56 | 57 | public Builder images(File[] val) { 58 | images = val; 59 | return this; 60 | } 61 | 62 | public Builder remark(String val) { 63 | remark = val; 64 | return this; 65 | } 66 | 67 | public Builder type(Integer val) { 68 | type = val; 69 | return this; 70 | } 71 | 72 | public SignPayload build() { 73 | Preconditions.checkArgument(!StringUtils.isEmpty(sign)&&sign.length()>=2 74 | &&sign.length()<=8, 75 | "sign should not be null or too long"); 76 | Preconditions.checkArgument(type != null&&type > 0 && type <= 7, "type should be between 1 and 7"); 77 | return new SignPayload(this); 78 | } 79 | } 80 | 81 | public String getSign() { 82 | return sign; 83 | } 84 | 85 | public File[] getImages() { 86 | return images; 87 | } 88 | 89 | public String getRemark() { 90 | return remark; 91 | } 92 | 93 | public Integer getType() { 94 | return type; 95 | } 96 | 97 | public static String getIMAGES() { 98 | return IMAGES; 99 | } 100 | 101 | public static String getSIGN() { 102 | return SIGN; 103 | } 104 | 105 | public static String getTYPE() { 106 | return TYPE; 107 | } 108 | 109 | public static String getREMARK() { 110 | return REMARK; 111 | } 112 | 113 | public JsonElement toJSON() { 114 | JsonObject json = new JsonObject(); 115 | 116 | if (!StringUtils.isEmpty(sign)) { 117 | json.addProperty(SIGN, sign); 118 | } 119 | 120 | if (type !=null && type > 0 && type <=7) { 121 | json.addProperty(TYPE, type); 122 | } 123 | 124 | if (remark != null) { 125 | json.addProperty(REMARK, remark); 126 | } 127 | return json; 128 | } 129 | 130 | @Override 131 | public String toString() { 132 | return gson.toJson(toJSON()); 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /src/main/java/cn/jsms/api/common/model/SMSPayload.java: -------------------------------------------------------------------------------- 1 | package cn.jsms.api.common.model; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | import com.google.gson.*; 7 | 8 | import cn.jiguang.common.utils.Preconditions; 9 | import cn.jiguang.common.utils.StringUtils; 10 | 11 | 12 | public class SMSPayload implements IModel { 13 | 14 | private static String MOBILE = "mobile"; 15 | private static String SIGN_ID = "sign_id"; 16 | private static String TEMP_ID = "temp_id"; 17 | private static String TTL = "ttl"; 18 | private static String TEMP_PARA = "temp_para"; 19 | private static String CODE = "code"; 20 | private static String VOICE_LANG = "voice_lang"; 21 | 22 | private String mobile; 23 | private int sign_id; 24 | private int temp_id; 25 | // Time to live parameter, the unit is second. 26 | private int ttl; 27 | private String code; 28 | private int voice_lang = -1; 29 | private final Map temp_para; 30 | private static Gson gson = new Gson(); 31 | 32 | private SMSPayload(String mobileNumber, int signId, int tempId, int ttl, String code, int voiceLang, Map temp_para) { 33 | this.mobile = mobileNumber; 34 | this.sign_id = signId; 35 | this.temp_id = tempId; 36 | this.ttl = ttl; 37 | this.code = code; 38 | this.voice_lang = voiceLang; 39 | this.temp_para = temp_para; 40 | } 41 | 42 | public static Builder newBuilder() { 43 | return new Builder(); 44 | } 45 | 46 | public static class Builder { 47 | private String mobile; 48 | private int sign_id; 49 | private int temp_id; 50 | private int ttl; 51 | private String code; 52 | private int voice_lang = -1; 53 | private Map tempParaBuilder; 54 | 55 | public Builder setMobileNumber(String mobileNumber) { 56 | this.mobile = mobileNumber.trim(); 57 | return this; 58 | } 59 | 60 | public Builder setSignId(int signId) { 61 | this.sign_id= signId; 62 | return this; 63 | } 64 | 65 | public Builder setTempId(int tempId) { 66 | this.temp_id = tempId; 67 | return this; 68 | } 69 | 70 | public Builder setTTL(int ttl) { 71 | this.ttl = ttl; 72 | return this; 73 | } 74 | 75 | public Builder setCode(String code) { 76 | Preconditions.checkArgument(code.length() >= 4 && code.length() <= 8, "Code's length should between 4 and 8"); 77 | this.code = code; 78 | return this; 79 | } 80 | 81 | public Builder setVoiceLang(int voiceLang) { 82 | Preconditions.checkArgument(voiceLang == 0 || voiceLang == 1 || voiceLang == 2, "Illegal voice lang. Voice lang should be 0, or 1 or 2"); 83 | this.voice_lang = voiceLang; 84 | return this; 85 | } 86 | 87 | public Builder setTempPara(Map temp_para) { 88 | Preconditions.checkArgument(! (null == temp_para), "temp_para should not be null."); 89 | if (null == tempParaBuilder) { 90 | tempParaBuilder = new HashMap(); 91 | } 92 | for (String key : temp_para.keySet()) { 93 | tempParaBuilder.put(key, temp_para.get(key)); 94 | } 95 | return this; 96 | } 97 | 98 | public Builder addTempPara(String key, String value) { 99 | Preconditions.checkArgument(! (null == key || null == value), "Key/Value should not be null."); 100 | if (null == tempParaBuilder) { 101 | tempParaBuilder = new HashMap(); 102 | } 103 | tempParaBuilder.put(key, value); 104 | return this; 105 | } 106 | 107 | public SMSPayload build() { 108 | Preconditions.checkArgument(null != mobile, "mobile number should not be null"); 109 | Preconditions.checkArgument(StringUtils.isNotEmpty(mobile), "mobile number should not be empty"); 110 | Preconditions.checkArgument(ttl >= 0, "ttl should not less 0"); 111 | Preconditions.checkArgument(temp_id >= 0, "temp id should not less 0"); 112 | 113 | return new SMSPayload(mobile, sign_id, temp_id, ttl, code, voice_lang, tempParaBuilder); 114 | } 115 | } 116 | 117 | public JsonElement toJSON() { 118 | JsonObject json = new JsonObject(); 119 | 120 | if (null != mobile) { 121 | json.addProperty(MOBILE, mobile); 122 | } 123 | 124 | if (sign_id > 0) { 125 | json.addProperty(SIGN_ID, sign_id); 126 | } 127 | 128 | if (temp_id > 0) { 129 | json.addProperty(TEMP_ID, temp_id); 130 | } 131 | 132 | if (ttl > 0) { 133 | json.addProperty(TTL, ttl); 134 | } 135 | 136 | if (voice_lang != -1) { 137 | json.addProperty(VOICE_LANG, voice_lang); 138 | } 139 | 140 | if (code != null) { 141 | json.addProperty(CODE, code); 142 | } 143 | 144 | JsonObject tempJson = null; 145 | if (null != temp_para) { 146 | tempJson = new JsonObject(); 147 | for (String key : temp_para.keySet()) { 148 | if (temp_para.get(key) != null) { 149 | tempJson.add(key, new JsonPrimitive(temp_para.get(key))); 150 | } else { 151 | tempJson.add(key, JsonNull.INSTANCE); 152 | } 153 | } 154 | } 155 | 156 | if (null != tempJson) { 157 | json.add(TEMP_PARA, tempJson); 158 | } 159 | 160 | return json; 161 | } 162 | 163 | @Override 164 | public String toString() { 165 | return gson.toJson(toJSON()); 166 | } 167 | } 168 | -------------------------------------------------------------------------------- /src/main/java/cn/jsms/api/schedule/model/ScheduleSMSPayload.java: -------------------------------------------------------------------------------- 1 | package cn.jsms.api.schedule.model; 2 | 3 | import cn.jiguang.common.utils.Preconditions; 4 | import cn.jiguang.common.utils.TimeUtils; 5 | import cn.jsms.api.common.model.IModel; 6 | import cn.jsms.api.common.model.RecipientPayload; 7 | import com.google.gson.*; 8 | 9 | import java.util.HashMap; 10 | import java.util.Map; 11 | 12 | public class ScheduleSMSPayload implements IModel { 13 | 14 | private static String SEND_TIME = "send_time"; 15 | private static String RECIPIENTS = "recipients"; 16 | private static String MOBILE = "mobile"; 17 | private static String SIGN_ID = "sign_id"; 18 | private static String TEMP_ID = "temp_id"; 19 | private static String TAG = "tag"; 20 | private static String TEMP_PARA = "temp_para"; 21 | 22 | private String sendTime; 23 | private String mobile; 24 | private int sign_id; 25 | private int temp_id; 26 | private String tag; 27 | private final Map temp_para; 28 | 29 | private static Gson gson = new Gson(); 30 | private JsonArray recipients; 31 | 32 | private ScheduleSMSPayload(String mobileNumber, int signId, String tag, int tempId, Map temp_para, String sendTime, JsonArray recipients) { 33 | this.mobile = mobileNumber; 34 | this.sign_id = signId; 35 | this.tag = tag; 36 | this.temp_id = tempId; 37 | this.temp_para = temp_para; 38 | this.sendTime = sendTime; 39 | this.recipients = recipients; 40 | } 41 | 42 | public static Builder newBuilder() { 43 | return new Builder(); 44 | } 45 | 46 | public static class Builder { 47 | private String mobile; 48 | private int sign_id; 49 | private int temp_id; 50 | private String tag; 51 | private Map tempParaBuilder; 52 | private String sendTime; 53 | private JsonArray recipients = new JsonArray(); 54 | 55 | public Builder setMobileNumber(String mobileNumber) { 56 | this.mobile = mobileNumber.trim(); 57 | return this; 58 | } 59 | 60 | public Builder setSignId(int signId) { 61 | this.sign_id = signId; 62 | return this; 63 | } 64 | 65 | public Builder setTempId(int tempId) { 66 | this.temp_id = tempId; 67 | return this; 68 | } 69 | 70 | public Builder setTag(String tag) { 71 | this.tag = tag; 72 | return this; 73 | } 74 | 75 | public Builder setTempPara(Map temp_para) { 76 | Preconditions.checkArgument(! (null == temp_para), "temp_para should not be null."); 77 | if (null == tempParaBuilder) { 78 | tempParaBuilder = new HashMap(); 79 | } 80 | for (String key : temp_para.keySet()) { 81 | tempParaBuilder.put(key, temp_para.get(key)); 82 | } 83 | return this; 84 | } 85 | 86 | public Builder addTempPara(String key, String value) { 87 | Preconditions.checkArgument(! (null == key || null == value), "Key/Value should not be null."); 88 | if (null == tempParaBuilder) { 89 | tempParaBuilder = new HashMap(); 90 | } 91 | tempParaBuilder.put(key, value); 92 | return this; 93 | } 94 | 95 | public Builder setSendTime(String sendTime) { 96 | this.sendTime = sendTime; 97 | return this; 98 | } 99 | 100 | public Builder setRecipients(RecipientPayload...recipients) { 101 | if (recipients == null) { 102 | return this; 103 | } 104 | 105 | for (RecipientPayload recipientPayload : recipients) { 106 | this.recipients.add(recipientPayload.toJSON()); 107 | } 108 | return this; 109 | } 110 | 111 | public Builder addRecipient(RecipientPayload recipientPayload) { 112 | Preconditions.checkArgument(null != recipientPayload, "RecipientPayload should not be null"); 113 | this.recipients.add(recipientPayload.toJSON()); 114 | return this; 115 | } 116 | 117 | public ScheduleSMSPayload build() { 118 | Preconditions.checkArgument(temp_id >= 0, "temp id should not less 0"); 119 | Preconditions.checkArgument(null != sendTime, "send time should not be null"); 120 | Preconditions.checkArgument(TimeUtils.isDateFormat(sendTime), "send time format is invalid"); 121 | return new ScheduleSMSPayload(mobile, sign_id, tag, temp_id, tempParaBuilder, sendTime, recipients); 122 | } 123 | } 124 | 125 | @Override 126 | public JsonElement toJSON() { 127 | JsonObject json = new JsonObject(); 128 | 129 | if (null != sendTime) { 130 | json.addProperty(SEND_TIME, sendTime); 131 | } 132 | 133 | if (null != mobile) { 134 | json.addProperty(MOBILE, mobile); 135 | } 136 | 137 | if (sign_id > 0) { 138 | json.addProperty(SIGN_ID, sign_id); 139 | } 140 | 141 | if (temp_id > 0) { 142 | json.addProperty(TEMP_ID, temp_id); 143 | } 144 | 145 | if (null != tag) { 146 | json.addProperty(TAG, tag); 147 | } 148 | 149 | JsonObject tempJson = null; 150 | if (null != temp_para) { 151 | tempJson = new JsonObject(); 152 | for (String key : temp_para.keySet()) { 153 | if (temp_para.get(key) != null) { 154 | tempJson.add(key, new JsonPrimitive(temp_para.get(key))); 155 | } else { 156 | tempJson.add(key, JsonNull.INSTANCE); 157 | } 158 | } 159 | } 160 | 161 | if (null != tempJson) { 162 | json.add(TEMP_PARA, tempJson); 163 | } 164 | 165 | if (null != recipients && recipients.size() > 0) { 166 | json.add(RECIPIENTS, recipients); 167 | } 168 | 169 | return json; 170 | } 171 | 172 | @Override 173 | public String toString() { 174 | return gson.toJson(toJSON()); 175 | } 176 | 177 | public String getMobile() { 178 | return this.mobile; 179 | } 180 | 181 | public JsonArray getRecipients() { 182 | return this.recipients; 183 | } 184 | } 185 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | 4 | cn.jpush.api 5 | jsms-client 6 | 1.2.10 7 | jar 8 | 9 | jsms-client 10 | http://maven.apache.org 11 | 12 | 13 | 14 | The Apache Software License, Version 2.0 15 | http://www.apache.org/licenses/LICENSE-2.0.txt 16 | repo 17 | 18 | 19 | 20 | 21 | org.sonatype.oss 22 | oss-parent 23 | 9 24 | 25 | 26 | 27 | https://github.com/jpush/jsms-api-java-client 28 | scm:git:git@github.com:jpush/jsms-api-java-client.git 29 | scm:git:git@github.com:jpush/jsms-api-java-client.git 30 | v1.2.8 31 | 32 | 33 | 34 | github 35 | UTF-8 36 | 1.6 37 | 1.6 38 | 39 | 40 | 41 | 42 | cn.jpush.api 43 | jiguang-common 44 | 1.0.8 45 | 46 | 47 | com.google.code.gson 48 | gson 49 | 2.3 50 | 51 | 52 | 53 | org.slf4j 54 | slf4j-api 55 | 1.7.7 56 | 57 | 58 | 59 | 60 | 61 | org.slf4j 62 | slf4j-log4j12 63 | 1.7.7 64 | test 65 | 66 | 67 | log4j 68 | log4j 69 | 1.2.17 70 | test 71 | 72 | 73 | 74 | junit 75 | junit 76 | 4.11 77 | test 78 | 79 | 80 | com.squareup.okhttp 81 | mockwebserver 82 | 2.0.0 83 | test 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | maven-compiler-plugin 93 | 3.5.1 94 | 95 | ${jdkVersion} 96 | ${jdkVersion} 97 | 1.7 98 | true 99 | true 100 | true 101 | true 102 | 103 | -Xlint:unchecked 104 | 105 | 106 | 107 | 108 | 109 | com.github.github 110 | site-maven-plugin 111 | 0.12 112 | 113 | Creating site for ${project.version} 114 | github 115 | 116 | 117 | 118 | 119 | site 120 | 121 | site 122 | 123 | 124 | 125 | 126 | 127 | org.apache.maven.plugins 128 | maven-surefire-plugin 129 | 2.17 130 | 131 | cn.jsms.api.FastTests 132 | -Dfile.encoding=UTF-8 133 | 134 | **/mock/*Test.java 135 | 136 | 137 | 138 | 139 | org.apache.maven.surefire 140 | surefire-junit47 141 | 2.17 142 | 143 | 144 | 145 | 146 | 147 | org.apache.maven.plugins 148 | maven-failsafe-plugin 149 | 2.17 150 | 151 | UTF-8 152 | cn.jsms.api.SlowTests 153 | -Dfile.encoding=UTF-8 154 | 155 | **/mock/*Test.java 156 | 157 | 158 | 159 | 160 | 161 | integration-test 162 | verify 163 | 164 | 165 | 166 | **/*.class 167 | 168 | 169 | 170 | 171 | 172 | 173 | org.apache.maven.surefire 174 | surefire-junit47 175 | 2.17 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | org.apache.maven.plugins 187 | maven-source-plugin 188 | 2.2.1 189 | 190 | 191 | attach-sources 192 | 193 | jar-no-fork 194 | 195 | 196 | 197 | 198 | 199 | org.apache.maven.plugins 200 | maven-javadoc-plugin 201 | 2.9.1 202 | 203 | 204 | attach-javadocs 205 | 206 | jar 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | org.apache.maven.plugins 215 | maven-gpg-plugin 216 | 1.5 217 | 218 | 219 | sign-artifacts 220 | verify 221 | 222 | sign 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | org.sonatype.plugins 231 | nexus-staging-maven-plugin 232 | 1.6.7 233 | true 234 | 235 | ossrh 236 | https://oss.sonatype.org/ 237 | 238 | false 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | ossrh 247 | https://oss.sonatype.org/content/repositories/snapshots/ 248 | 249 | 250 | ossrh 251 | https://oss.sonatype.org/service/local/staging/deploy/maven2/ 252 | 253 | 254 | 255 | 256 | 257 | 258 | org.apache.maven.plugins 259 | maven-project-info-reports-plugin 260 | 2.8.1 261 | 262 | 263 | 264 | dependencies 265 | license 266 | scm 267 | 268 | 269 | 270 | 271 | 272 | 273 | org.apache.maven.plugins 274 | maven-javadoc-plugin 275 | 2.10.3 276 | 277 | resources/javadoc-overview.html 278 | 279 | 280 | 281 | 282 | 283 | 284 | 285 | -------------------------------------------------------------------------------- /src/main/java/cn/jsms/api/JSMSClient.java: -------------------------------------------------------------------------------- 1 | package cn.jsms.api; 2 | 3 | import cn.jiguang.common.connection.HttpProxy; 4 | import cn.jiguang.common.resp.APIConnectionException; 5 | import cn.jiguang.common.resp.APIRequestException; 6 | import cn.jiguang.common.resp.ResponseWrapper; 7 | import cn.jsms.api.account.AccountBalanceResult; 8 | import cn.jsms.api.account.AppBalanceResult; 9 | import cn.jsms.api.common.JSMSConfig; 10 | import cn.jsms.api.common.SMSClient; 11 | import cn.jsms.api.common.model.BatchSMSPayload; 12 | import cn.jsms.api.common.model.SMSPayload; 13 | import cn.jsms.api.common.model.BatchSMSResult; 14 | import cn.jsms.api.schedule.model.ScheduleResult; 15 | import cn.jsms.api.schedule.model.ScheduleSMSPayload; 16 | import cn.jsms.api.schedule.model.ScheduleSMSResult; 17 | import cn.jsms.api.sign.DefaultSignPayload; 18 | import cn.jsms.api.sign.SignInfoResult; 19 | import cn.jsms.api.sign.SignPayload; 20 | import cn.jsms.api.sign.SignResult; 21 | import cn.jsms.api.template.SendTempSMSResult; 22 | import cn.jsms.api.template.TempSMSResult; 23 | import cn.jsms.api.template.TemplatePayload; 24 | 25 | public class JSMSClient { 26 | 27 | private SMSClient _smsClient; 28 | 29 | public JSMSClient(String masterSecret, String appkey) { 30 | _smsClient = new SMSClient(masterSecret, appkey); 31 | } 32 | 33 | public JSMSClient(String masterSecret, String appkey, HttpProxy proxy, JSMSConfig conf) { 34 | _smsClient = new SMSClient(masterSecret, appkey, proxy, conf); 35 | } 36 | 37 | public SMSClient getSMSClient() { 38 | return this._smsClient; 39 | } 40 | 41 | /** 42 | * Send SMS verification code to mobile 43 | * @param payload include two parameters: mobile number and templete id. The second parameter is optional. 44 | * @return return SendSMSResult which includes msg_id 45 | * @throws APIConnectionException connection exception 46 | * @throws APIRequestException request exception 47 | */ 48 | public SendSMSResult sendSMSCode(SMSPayload payload) 49 | throws APIConnectionException, APIRequestException { 50 | return _smsClient.sendSMSCode(payload); 51 | } 52 | 53 | /** 54 | * Send SMS verification code to server, to verify if the code valid 55 | * @param msgId The message id of the verification code 56 | * @param code Verification code 57 | * @return return ValidSMSResult includes is_valid 58 | * @throws APIConnectionException connection exception 59 | * @throws APIRequestException request exception 60 | */ 61 | public ValidSMSResult sendValidSMSCode(String msgId, String code) 62 | throws APIConnectionException, APIRequestException { 63 | return _smsClient.sendValidSMSCode(msgId, code); 64 | } 65 | 66 | /** 67 | * Send voice SMS verification code to mobile 68 | * @param payload payload includes two parameters: mobile number and ttl(time to live), 69 | * the second one is optional(if miss ttl, will use default value 60 seconds). 70 | * @return return SendSMSResult which includes msg_id 71 | * @throws APIConnectionException connection exception 72 | * @throws APIRequestException request exception 73 | */ 74 | public SendSMSResult sendVoiceSMSCode(SMSPayload payload) 75 | throws APIConnectionException, APIRequestException { 76 | return _smsClient.sendVoiceSMSCode(payload); 77 | } 78 | 79 | /** 80 | * Send template SMS to mobile 81 | * @param payload payload includes mobile, temp_id and temp_para, the temp_para is a map, 82 | * which's key is what you had set in jiguang portal 83 | * @return return SendSMSResult which includes msg_id 84 | * @throws APIConnectionException connection exception 85 | * @throws APIRequestException request exception 86 | */ 87 | public SendSMSResult sendTemplateSMS(SMSPayload payload) 88 | throws APIConnectionException, APIRequestException { 89 | return _smsClient.sendTemplateSMS(payload); 90 | } 91 | 92 | /** 93 | * Send a batch of template SMS 94 | * @param payload BatchSMSPayload 95 | * @return BatchSMSResult 96 | * @throws APIConnectionException connect exception 97 | * @throws APIRequestException request exception 98 | */ 99 | public BatchSMSResult sendBatchTemplateSMS(BatchSMSPayload payload) 100 | throws APIConnectionException, APIRequestException { 101 | return _smsClient.sendBatchTemplateSMS(payload); 102 | } 103 | 104 | /** 105 | * Submit a mission that sending a template SMS with pointed schedule 106 | * @param payload ScheduleSMSPayload 107 | * @return ScheduleResult which includes schedule_id 108 | * @throws APIConnectionException connect exception 109 | * @throws APIRequestException request exception 110 | */ 111 | public ScheduleResult sendScheduleSMS(ScheduleSMSPayload payload) 112 | throws APIConnectionException, APIRequestException { 113 | return _smsClient.sendScheduleSMS(payload); 114 | } 115 | 116 | /** 117 | * Modify SMS with schedule 118 | * @param payload ScheduleSMSPayload 119 | * @param scheduleId id 120 | * @return ScheduleResult which includes schedule_id 121 | * @throws APIConnectionException connect exception 122 | * @throws APIRequestException request exception 123 | */ 124 | public ScheduleResult updateScheduleSMS(ScheduleSMSPayload payload, String scheduleId) 125 | throws APIConnectionException, APIRequestException { 126 | return _smsClient.updateScheduleSMS(payload, scheduleId); 127 | } 128 | 129 | /** 130 | * Submit a mission that sending a batch of SMS with schedule 131 | * @param payload Payload should include sendTime and recipients 132 | * @return BatchSMSResult 133 | * @throws APIConnectionException connect exception 134 | * @throws APIRequestException request exception 135 | */ 136 | public BatchSMSResult sendBatchScheduleSMS(ScheduleSMSPayload payload) 137 | throws APIConnectionException, APIRequestException { 138 | return _smsClient.sendBatchScheduleSMS(payload); 139 | } 140 | 141 | /** 142 | * Update batch of SMS with schedule 143 | * @param payload ScheduleSMSPayload 144 | * @param scheduleId id 145 | * @return BatchSMSResult 146 | * @throws APIConnectionException connection exception 147 | * @throws APIRequestException request exception 148 | */ 149 | public BatchSMSResult updateBatchScheduleSMS(ScheduleSMSPayload payload, String scheduleId) 150 | throws APIConnectionException, APIRequestException { 151 | return _smsClient.updateBatchScheduleSMS(payload, scheduleId); 152 | } 153 | 154 | /** 155 | * Get schedule SMS by scheduleId 156 | * @param scheduleId id 157 | * @return ScheduleSMSResult 158 | * @throws APIConnectionException connection exception 159 | * @throws APIRequestException request exception 160 | */ 161 | public ScheduleSMSResult getScheduleSMS(String scheduleId) throws APIConnectionException, APIRequestException { 162 | return _smsClient.getScheduleSMS(scheduleId); 163 | } 164 | 165 | /** 166 | * Delete schedule SMS by scheduleId 167 | * @param scheduleId id 168 | * @return No content 169 | * @throws APIConnectionException connect exception 170 | * @throws APIRequestException request exception 171 | */ 172 | public ResponseWrapper deleteScheduleSMS(String scheduleId) throws APIConnectionException, APIRequestException { 173 | return _smsClient.deleteScheduleSMS(scheduleId); 174 | } 175 | 176 | /** 177 | * Get account's SMS balance 178 | * @return AccountBalanceResult 179 | * @throws APIConnectionException connect exception 180 | * @throws APIRequestException request exception 181 | */ 182 | public AccountBalanceResult getSMSBalance() throws APIConnectionException, APIRequestException { 183 | return _smsClient.getSMSBalance(); 184 | } 185 | 186 | /** 187 | * Get app's SMS balance of an account 188 | * @return AppBalanceResult 189 | * @throws APIConnectionException connect exception 190 | * @throws APIRequestException request exception 191 | */ 192 | public AppBalanceResult getAppSMSBalance() throws APIConnectionException, APIRequestException { 193 | return _smsClient.getAppSMSBalance(); 194 | } 195 | 196 | //============ Template API ============== 197 | 198 | /** 199 | * Create template sms. 200 | * @param payload {@link TemplatePayload } 201 | * @return {@link SendTempSMSResult }, include temp_id 202 | * @throws APIConnectionException connect exception 203 | * @throws APIRequestException request exception 204 | */ 205 | public SendTempSMSResult createTemplate(TemplatePayload payload) throws APIConnectionException, APIRequestException { 206 | return _smsClient.createTemplate(payload); 207 | } 208 | 209 | /** 210 | * update template sms. Template can be modified ONLY when status is not approved 211 | * @param payload {@link TemplatePayload } 212 | * @param tempId temp id 213 | * @return {@link SendTempSMSResult }, include temp_id 214 | * @throws APIConnectionException connect exception 215 | * @throws APIRequestException request exception 216 | */ 217 | public SendTempSMSResult updateTemplate(TemplatePayload payload, int tempId) throws APIConnectionException, APIRequestException { 218 | return _smsClient.updateTemplate(payload, tempId); 219 | } 220 | 221 | /** 222 | * check template by id 223 | * @param tempId necessary 224 | * @return {@link TempSMSResult} 225 | * @throws APIConnectionException connect exception 226 | * @throws APIRequestException request exception 227 | */ 228 | public TempSMSResult checkTemplate(int tempId) throws APIConnectionException, APIRequestException { 229 | return _smsClient.checkTemplate(tempId); 230 | } 231 | 232 | /** 233 | * Delete template by id 234 | * @param tempId necessary 235 | * @return No content 236 | * @throws APIConnectionException connect exception 237 | * @throws APIRequestException request exception 238 | */ 239 | public ResponseWrapper deleteTemplate(int tempId) throws APIConnectionException, APIRequestException { 240 | return _smsClient.deleteTemplate(tempId); 241 | } 242 | 243 | /** 244 | * create sign 245 | * @param payload {@link SignPayload } 246 | * @return {@link SignResult} 247 | * @throws APIConnectionException connect exception 248 | * @throws APIRequestException request exception 249 | */ 250 | public SignResult createSign(SignPayload payload) throws APIConnectionException, APIRequestException{ 251 | return _smsClient.createSign(payload); 252 | } 253 | 254 | /** 255 | * update sign 256 | * @param payload {@link SignPayload } 257 | * @param signId necessary 258 | * @return {@link SignResult} 259 | * @throws APIConnectionException connect exception 260 | * @throws APIRequestException request exception 261 | */ 262 | public SignResult updateSign(SignPayload payload, int signId) throws APIConnectionException, APIRequestException{ 263 | return _smsClient.updateSign(payload, signId); 264 | } 265 | 266 | /** 267 | * delete sig by id 268 | * @param signId necessary 269 | * @return No content 270 | * @throws APIConnectionException connect exception 271 | * @throws APIRequestException request exception 272 | */ 273 | public ResponseWrapper deleteSign(int signId) throws APIConnectionException, APIRequestException{ 274 | return _smsClient.deleteSign(signId); 275 | } 276 | 277 | /** 278 | * get sign by id 279 | * @param signId necessary 280 | * @return {@link SignInfoResult} 281 | * @throws APIConnectionException connect exception 282 | * @throws APIRequestException request exception 283 | */ 284 | public SignInfoResult checkSign(int signId) throws APIConnectionException, APIRequestException{ 285 | return _smsClient.checkSign(signId); 286 | } 287 | 288 | // /** 289 | // * set default sign 290 | // * @param payload 291 | // * @return 292 | // * @throws APIConnectionException 293 | // * @throws APIRequestException 294 | // */ 295 | // public ResponseWrapper setDefaultSign(DefaultSignPayload payload) throws APIConnectionException, APIRequestException{ 296 | // return _smsClient.setDefaultSign(payload); 297 | // } 298 | } 299 | -------------------------------------------------------------------------------- /example/main/java/cn/jsms/api/JSMSExample.java: -------------------------------------------------------------------------------- 1 | package cn.jsms.api; 2 | 3 | import cn.jiguang.common.ClientConfig; 4 | import cn.jiguang.common.ServiceHelper; 5 | import cn.jiguang.common.connection.ApacheHttpClient; 6 | import cn.jiguang.common.resp.ResponseWrapper; 7 | import cn.jsms.api.account.AccountBalanceResult; 8 | import cn.jsms.api.account.AppBalanceResult; 9 | import cn.jsms.api.common.model.BatchSMSPayload; 10 | import cn.jsms.api.common.model.BatchSMSResult; 11 | import cn.jsms.api.common.model.RecipientPayload; 12 | import cn.jsms.api.schedule.model.ScheduleResult; 13 | import cn.jsms.api.schedule.model.ScheduleSMSPayload; 14 | import cn.jsms.api.sign.DefaultSignPayload; 15 | import cn.jsms.api.sign.SignInfoResult; 16 | import cn.jsms.api.sign.SignPayload; 17 | import cn.jsms.api.sign.SignResult; 18 | import cn.jsms.api.template.SendTempSMSResult; 19 | import cn.jsms.api.template.TempSMSResult; 20 | import cn.jsms.api.template.TemplatePayload; 21 | import org.slf4j.Logger; 22 | import org.slf4j.LoggerFactory; 23 | 24 | import cn.jiguang.common.resp.APIConnectionException; 25 | import cn.jiguang.common.resp.APIRequestException; 26 | import cn.jsms.api.common.SMSClient; 27 | import cn.jsms.api.common.model.SMSPayload; 28 | 29 | import java.io.File; 30 | import java.security.KeyStore; 31 | import java.util.ArrayList; 32 | import java.util.List; 33 | 34 | 35 | public class JSMSExample { 36 | 37 | protected static final Logger LOG = LoggerFactory.getLogger(JSMSExample.class); 38 | 39 | private static final String appkey = "09198ca47f1cc830aa3e064c"; 40 | private static final String masterSecret = "4258ba884dbbceefe3cdb737"; 41 | 42 | private static final String devKey = "242780bfdd7315dc1989fedb"; 43 | private static final String devSecret = "2f5ced2bef64167950e63d13"; 44 | 45 | public static void main(String[] args) { 46 | // testSendSMSCode(); 47 | // testCreateSign();pass 48 | // testUpdateSign();no pass 49 | // testCheckSign();pass 50 | testUpdateSign(); 51 | // testSendVoiceSMSCode(); 52 | // testSendTemplateSMS(); 53 | } 54 | 55 | public static void testSendSMSCode() { 56 | SMSClient client = new SMSClient(masterSecret, appkey); 57 | SMSPayload payload = SMSPayload.newBuilder() 58 | .setMobileNumber("13800138000") 59 | .setTempId(1) 60 | .build(); 61 | try { 62 | SendSMSResult res = client.sendSMSCode(payload); 63 | System.out.println(res.toString()); 64 | LOG.info(res.toString()); 65 | } catch (APIConnectionException e) { 66 | LOG.error("Connection error. Should retry later. ", e); 67 | } catch (APIRequestException e) { 68 | LOG.error("Error response from JPush server. Should review and fix it. ", e); 69 | LOG.info("HTTP Status: " + e.getStatus()); 70 | LOG.info("Error Message: " + e.getMessage()); 71 | } 72 | } 73 | 74 | public static void testSendSMSWithIHttpClient() { 75 | SMSClient client = new SMSClient(masterSecret, appkey); 76 | String authCode = ServiceHelper.getBasicAuthorization(appkey, masterSecret); 77 | ApacheHttpClient httpClient = new ApacheHttpClient(authCode, null, ClientConfig.getInstance()); 78 | // NettyHttpClient httpClient = new NettyHttpClient(authCode, null, ClientConfig.getInstance()); 79 | // ApacheHttpClient httpClient = new ApacheHttpClient(authCode, null, ClientConfig.getInstance()); 80 | // 可以切换 HttpClient,默认使用的是 NativeHttpClient 81 | client.setHttpClient(httpClient); 82 | // 如果使用 NettyHttpClient,发送完请求后要调用 close 方法 83 | // client.close(); 84 | SMSPayload payload = SMSPayload.newBuilder() 85 | .setMobileNumber("13800138000") 86 | .setTempId(1) 87 | .build(); 88 | try { 89 | SendSMSResult res = client.sendSMSCode(payload); 90 | System.out.println(res.toString()); 91 | LOG.info(res.toString()); 92 | } catch (APIConnectionException e) { 93 | LOG.error("Connection error. Should retry later. ", e); 94 | } catch (APIRequestException e) { 95 | LOG.error("Error response from JPush server. Should review and fix it. ", e); 96 | LOG.info("HTTP Status: " + e.getStatus()); 97 | LOG.info("Error Message: " + e.getMessage()); 98 | } 99 | } 100 | 101 | public static void testSendValidSMSCode() { 102 | SMSClient client = new SMSClient(masterSecret, appkey); 103 | try { 104 | ValidSMSResult res = client.sendValidSMSCode("01658697-45d9-4644-996d-69a1b14e2bb8", "556618"); 105 | System.out.println(res.toString()); 106 | LOG.info(res.toString()); 107 | } catch (APIConnectionException e) { 108 | e.printStackTrace(); 109 | System.out.println(e.getMessage()); 110 | LOG.error("Connection error. Should retry later. ", e); 111 | } catch (APIRequestException e) { 112 | e.printStackTrace(); 113 | if (e.getErrorCode() == 50010) { 114 | // do something 115 | } 116 | System.out.println(e.getStatus() + " errorCode: " + e.getErrorCode() + " " + e.getErrorMessage()); 117 | LOG.error("Error response from JPush server. Should review and fix it. ", e); 118 | LOG.info("HTTP Status: " + e.getStatus()); 119 | LOG.info("Error Message: " + e.getMessage()); 120 | } 121 | } 122 | 123 | /** 124 | * The default value of ttl is 60 seconds. 125 | */ 126 | public static void testSendVoiceSMSCode() { 127 | SMSClient client = new SMSClient(masterSecret, appkey); 128 | SMSPayload payload = SMSPayload.newBuilder() 129 | .setMobileNumber("13800138000") 130 | .setTTL(90) 131 | .build(); 132 | try { 133 | SendSMSResult res = client.sendVoiceSMSCode(payload); 134 | LOG.info(res.toString()); 135 | } catch (APIRequestException e) { 136 | LOG.error("Error response from JPush server. Should review and fix it. ", e); 137 | LOG.info("HTTP Status: " + e.getStatus()); 138 | LOG.info("Error Message: " + e.getMessage()); 139 | } catch (APIConnectionException e) { 140 | LOG.error("Connection error. Should retry later. ", e); 141 | } 142 | } 143 | 144 | public static void testSendTemplateSMS() { 145 | SMSClient client = new SMSClient(masterSecret, appkey); 146 | SMSPayload payload = SMSPayload.newBuilder() 147 | .setMobileNumber("13800138000") 148 | .setTempId(1) 149 | .addTempPara("test", "jpush") 150 | .build(); 151 | try { 152 | SendSMSResult res = client.sendTemplateSMS(payload); 153 | LOG.info(res.toString()); 154 | } catch (APIRequestException e) { 155 | LOG.error("Error response from JPush server. Should review and fix it. ", e); 156 | LOG.info("HTTP Status: " + e.getStatus()); 157 | LOG.info("Error Message: " + e.getMessage()); 158 | } catch (APIConnectionException e) { 159 | LOG.error("Connection error. Should retry later. ", e); 160 | } 161 | } 162 | 163 | public static void testSendBatchTemplateSMS() { 164 | SMSClient client = new SMSClient(masterSecret, appkey); 165 | List list = new ArrayList(); 166 | RecipientPayload recipientPayload1 = new RecipientPayload.Builder() 167 | .setMobile("13800138000") 168 | .addTempPara("code", "638938") 169 | .build(); 170 | RecipientPayload recipientPayload2 = new RecipientPayload.Builder() 171 | .setMobile("13800138000") 172 | .addTempPara("code", "829302") 173 | .build(); 174 | list.add(recipientPayload1); 175 | list.add(recipientPayload2); 176 | RecipientPayload[] recipientPayloads = new RecipientPayload[list.size()]; 177 | BatchSMSPayload smsPayload = BatchSMSPayload.newBuilder() 178 | .setTempId(1) 179 | .setRecipients(list.toArray(recipientPayloads)) 180 | .build(); 181 | try { 182 | BatchSMSResult result = client.sendBatchTemplateSMS(smsPayload); 183 | LOG.info("Got result: " + result); 184 | } catch (APIConnectionException e) { 185 | LOG.error("Connection error. Should retry later. ", e); 186 | } catch (APIRequestException e) { 187 | LOG.error("Error response from JPush server. Should review and fix it. ", e); 188 | LOG.info("HTTP Status: " + e.getStatus()); 189 | LOG.info("Error Message: " + e.getMessage()); 190 | } 191 | } 192 | 193 | public static void testSendScheduleSMS() { 194 | SMSClient client = new SMSClient(masterSecret, appkey); 195 | ScheduleSMSPayload payload = ScheduleSMSPayload.newBuilder() 196 | .setMobileNumber("13800138000") 197 | .setTempId(1111) 198 | .setSendTime("2017-07-31 16:17:00") 199 | .addTempPara("number", "798560") 200 | .build(); 201 | try { 202 | ScheduleResult result = client.sendScheduleSMS(payload); 203 | LOG.info(result.toString()); 204 | } catch (APIConnectionException e) { 205 | LOG.error("Connection error. Should retry later. ", e); 206 | } catch (APIRequestException e) { 207 | LOG.error("Error response from JPush server. Should review and fix it. ", e); 208 | LOG.info("HTTP Status: " + e.getStatus()); 209 | LOG.info("Error Message: " + e.getMessage()); 210 | } 211 | } 212 | 213 | public static void testUpdateScheduleSMS() { 214 | SMSClient client = new SMSClient(masterSecret, appkey); 215 | ScheduleSMSPayload payload = ScheduleSMSPayload.newBuilder() 216 | .setMobileNumber("13800138000") 217 | .setTempId(1111) 218 | .setSendTime("2017-07-31 15:00:00") 219 | .addTempPara("number", "110110") 220 | .build(); 221 | try { 222 | ScheduleResult result = client.updateScheduleSMS(payload, "dsfd"); 223 | LOG.info(result.toString()); 224 | } catch (APIConnectionException e) { 225 | LOG.error("Connection error. Should retry later. ", e); 226 | } catch (APIRequestException e) { 227 | LOG.error("Error response from JPush server. Should review and fix it. ", e); 228 | LOG.info("HTTP Status: " + e.getStatus()); 229 | LOG.info("Error Message: " + e.getMessage()); 230 | } 231 | } 232 | 233 | public static void testSendBatchScheduleSMS() { 234 | SMSClient client = new SMSClient(masterSecret, appkey); 235 | List list = new ArrayList(); 236 | RecipientPayload recipientPayload1 = new RecipientPayload.Builder() 237 | .setMobile("13800138000") 238 | .addTempPara("number", "638938") 239 | .build(); 240 | RecipientPayload recipientPayload2 = new RecipientPayload.Builder() 241 | .setMobile("13800138001") 242 | .addTempPara("number", "829302") 243 | .build(); 244 | list.add(recipientPayload1); 245 | list.add(recipientPayload2); 246 | RecipientPayload[] recipientPayloads = new RecipientPayload[list.size()]; 247 | ScheduleSMSPayload smsPayload = ScheduleSMSPayload.newBuilder() 248 | .setSendTime("2017-07-31 16:00:00") 249 | .setTempId(1245) 250 | .setRecipients(list.toArray(recipientPayloads)) 251 | .build(); 252 | try { 253 | BatchSMSResult result = client.sendBatchScheduleSMS(smsPayload); 254 | LOG.info(result.toString()); 255 | } catch (APIConnectionException e) { 256 | LOG.error("Connection error. Should retry later. ", e); 257 | } catch (APIRequestException e) { 258 | LOG.error("Error response from JPush server. Should review and fix it. ", e); 259 | LOG.info("HTTP Status: " + e.getStatus()); 260 | LOG.info("Error Message: " + e.getMessage()); 261 | } 262 | } 263 | 264 | public static void testUpdateBatchScheduleSMS() { 265 | SMSClient client = new SMSClient(masterSecret, appkey); 266 | List list = new ArrayList(); 267 | RecipientPayload recipientPayload1 = new RecipientPayload.Builder() 268 | .setMobile("13800138000") 269 | .addTempPara("number", "328393") 270 | .build(); 271 | RecipientPayload recipientPayload2 = new RecipientPayload.Builder() 272 | .setMobile("13800138001") 273 | .addTempPara("number", "489042") 274 | .build(); 275 | list.add(recipientPayload1); 276 | list.add(recipientPayload2); 277 | RecipientPayload[] recipientPayloads = new RecipientPayload[list.size()]; 278 | ScheduleSMSPayload smsPayload = ScheduleSMSPayload.newBuilder() 279 | .setSendTime("2017-07-31 16:00:00") 280 | .setTempId(1245) 281 | .setRecipients(list.toArray(recipientPayloads)) 282 | .build(); 283 | try { 284 | BatchSMSResult result = client.updateBatchScheduleSMS(smsPayload, "dfs"); 285 | LOG.info(result.toString()); 286 | } catch (APIConnectionException e) { 287 | LOG.error("Connection error. Should retry later. ", e); 288 | } catch (APIRequestException e) { 289 | LOG.error("Error response from JPush server. Should review and fix it. ", e); 290 | LOG.info("HTTP Status: " + e.getStatus()); 291 | LOG.info("Error Message: " + e.getMessage()); 292 | } 293 | } 294 | 295 | public static void testDeleteScheduleSMS() { 296 | SMSClient client = new SMSClient(masterSecret, appkey); 297 | try { 298 | ResponseWrapper result = client.deleteScheduleSMS("sd"); 299 | LOG.info("Response content: " + result.responseContent + " response code: " + result.responseCode); 300 | } catch (APIConnectionException e) { 301 | LOG.error("Connection error. Should retry later. ", e); 302 | } catch (APIRequestException e) { 303 | LOG.error("Error response from JPush server. Should review and fix it. ", e); 304 | LOG.info("HTTP Status: " + e.getStatus()); 305 | LOG.info("Error Message: " + e.getMessage()); 306 | } 307 | } 308 | 309 | public static void testGetAccountSMSBalance() { 310 | SMSClient client = new SMSClient(devSecret, devKey); 311 | try { 312 | AccountBalanceResult result = client.getSMSBalance(); 313 | LOG.info(result.toString()); 314 | } catch (APIConnectionException e) { 315 | LOG.error("Connection error. Should retry later. ", e); 316 | } catch (APIRequestException e) { 317 | LOG.error("Error response from JPush server. Should review and fix it. ", e); 318 | LOG.info("HTTP Status: " + e.getStatus()); 319 | LOG.info("Error Message: " + e.getMessage()); 320 | } 321 | } 322 | 323 | public static void testGetAppSMSBalance() { 324 | SMSClient client = new SMSClient(masterSecret, appkey); 325 | try { 326 | AppBalanceResult result = client.getAppSMSBalance(); 327 | LOG.info(result.toString()); 328 | } catch (APIConnectionException e) { 329 | LOG.error("Connection error. Should retry later. ", e); 330 | } catch (APIRequestException e) { 331 | LOG.error("Error response from JPush server. Should review and fix it. ", e); 332 | LOG.info("HTTP Status: " + e.getStatus()); 333 | LOG.info("Error Message: " + e.getMessage()); 334 | } 335 | } 336 | 337 | 338 | public void testCreateTemplate() { 339 | try { 340 | SMSClient client = new SMSClient(masterSecret, appkey); 341 | TemplatePayload payload = TemplatePayload.newBuilder() 342 | .setTemplate("您好,您的验证码是{{code}},2分钟内有效!") 343 | .setType(1) 344 | .setTTL(120) 345 | .setRemark("验证短信") 346 | .build(); 347 | SendTempSMSResult result = client.createTemplate(payload); 348 | LOG.info(result.toString()); 349 | } catch (APIConnectionException e) { 350 | LOG.error("Connection error. Should retry later. ", e); 351 | } catch (APIRequestException e) { 352 | LOG.error("Error response from JPush server. Should review and fix it. ", e); 353 | LOG.info("HTTP Status: " + e.getStatus()); 354 | LOG.info("Error Message: " + e.getMessage()); 355 | } 356 | } 357 | 358 | // 只有审核不通过状态的模板才允许修改 359 | public void testUpdateTemplate() { 360 | try { 361 | SMSClient client = new SMSClient(masterSecret, appkey); 362 | TemplatePayload payload = TemplatePayload.newBuilder() 363 | .setTempId(12345) 364 | .setTemplate("您好,您的验证码是{{code}},2分钟内有效!") 365 | .setType(1) 366 | .setTTL(120) 367 | .setRemark("验证短信") 368 | .build(); 369 | SendTempSMSResult result = client.updateTemplate(payload, 12345); 370 | LOG.info(result.toString()); 371 | } catch (APIConnectionException e) { 372 | LOG.error("Connection error. Should retry later. ", e); 373 | } catch (APIRequestException e) { 374 | LOG.error("Error response from JPush server. Should review and fix it. ", e); 375 | LOG.info("HTTP Status: " + e.getStatus()); 376 | LOG.info("Error Message: " + e.getMessage()); 377 | } 378 | } 379 | 380 | public void testCheckTemplate() { 381 | try { 382 | SMSClient client = new SMSClient(masterSecret, appkey); 383 | TempSMSResult result = client.checkTemplate(144923); 384 | LOG.info(result.toString()); 385 | } catch (APIConnectionException e) { 386 | LOG.error("Connection error. Should retry later. ", e); 387 | } catch (APIRequestException e) { 388 | LOG.error("Error response from JPush server. Should review and fix it. ", e); 389 | LOG.info("HTTP Status: " + e.getStatus()); 390 | LOG.info("Error Message: " + e.getMessage()); 391 | } 392 | } 393 | 394 | public void testDeleteTemplate() { 395 | try { 396 | SMSClient client = new SMSClient(masterSecret, appkey); 397 | ResponseWrapper result = client.deleteTemplate(144923); 398 | LOG.info(result.toString()); 399 | } catch (APIConnectionException e) { 400 | LOG.error("Connection error. Should retry later. ", e); 401 | } catch (APIRequestException e) { 402 | LOG.error("Error response from JPush server. Should review and fix it. ", e); 403 | LOG.info("HTTP Status: " + e.getStatus()); 404 | LOG.info("Error Message: " + e.getMessage()); 405 | } 406 | } 407 | 408 | public static void testCreateSign(){ 409 | try { 410 | File avatar_file = new File("C:\\Users\\jiguang\\Desktop\\sign.jpg"); 411 | File[] files = new File[1]; 412 | files[0] = avatar_file; 413 | SMSClient client = new SMSClient(masterSecret, appkey); 414 | SignPayload payload = SignPayload.newBuilder(). 415 | sign("SDK6"). 416 | type(1). 417 | remark("SDK测试"). 418 | images(files). 419 | build(); 420 | SignResult result = client.createSign(payload); 421 | LOG.info(result.toString()); 422 | }catch (APIConnectionException e) { 423 | LOG.error("Connection error. Should retry later. ", e); 424 | } catch (APIRequestException e) { 425 | LOG.error("Error response from JPush server. Should review and fix it. ", e); 426 | LOG.info("HTTP Status: " + e.getStatus()); 427 | LOG.info("Error Message: " + e.getMessage()); 428 | } 429 | } 430 | 431 | public static void testUpdateSign(){ 432 | try { 433 | File avatar_file = new File("C:\\Users\\jiguang\\Desktop\\testSign.jpg"); 434 | File[] files = new File[1]; 435 | files[0] = avatar_file; 436 | SMSClient client = new SMSClient(masterSecret, appkey); 437 | SignPayload payload = SignPayload.newBuilder(). 438 | sign("SDK6"). 439 | type(1). 440 | remark("SDK测试"). 441 | images(files). 442 | build(); 443 | SignResult result = client.updateSign(payload,10859); 444 | LOG.info(result.toString()); 445 | }catch (APIConnectionException e) { 446 | LOG.error("Connection error. Should retry later. ", e); 447 | } catch (APIRequestException e) { 448 | LOG.error("Error response from JPush server. Should review and fix it. ", e); 449 | LOG.info("HTTP Status: " + e.getStatus()); 450 | LOG.info("Error Message: " + e.getMessage()); 451 | } 452 | } 453 | 454 | public static void testCheckSign(){ 455 | try { 456 | SMSClient client = new SMSClient(masterSecret, appkey); 457 | SignInfoResult result = client.checkSign(10859); 458 | LOG.info(result.toString()); 459 | }catch (APIConnectionException e) { 460 | LOG.error("Connection error. Should retry later. ", e); 461 | } catch (APIRequestException e) { 462 | LOG.error("Error response from JPush server. Should review and fix it. ", e); 463 | LOG.info("HTTP Status: " + e.getStatus()); 464 | LOG.info("Error Message: " + e.getMessage()); 465 | } 466 | } 467 | 468 | public static void testDeleteSign(){ 469 | try { 470 | SMSClient client = new SMSClient(masterSecret, appkey); 471 | ResponseWrapper result = client.deleteSign(10859); 472 | LOG.info(result.toString()); 473 | }catch (APIConnectionException e) { 474 | LOG.error("Connection error. Should retry later. ", e); 475 | } catch (APIRequestException e) { 476 | LOG.error("Error response from JPush server. Should review and fix it. ", e); 477 | LOG.info("HTTP Status: " + e.getStatus()); 478 | LOG.info("Error Message: " + e.getMessage()); 479 | } 480 | } 481 | 482 | 483 | } 484 | -------------------------------------------------------------------------------- /src/test/java/cn/jsms/api/sms/SMSClientTest.java: -------------------------------------------------------------------------------- 1 | package cn.jsms.api.sms; 2 | 3 | import static org.junit.Assert.assertEquals; 4 | import static org.junit.Assert.assertTrue; 5 | 6 | import cn.jiguang.common.resp.ResponseWrapper; 7 | import cn.jsms.api.account.AccountBalanceResult; 8 | import cn.jsms.api.account.AppBalanceResult; 9 | import cn.jsms.api.common.model.BatchSMSPayload; 10 | import cn.jsms.api.common.model.BatchSMSResult; 11 | import cn.jsms.api.common.model.RecipientPayload; 12 | import cn.jsms.api.schedule.model.ScheduleResult; 13 | import cn.jsms.api.schedule.model.ScheduleSMSPayload; 14 | import cn.jsms.api.sign.SignPayload; 15 | import cn.jsms.api.sign.SignResult; 16 | import cn.jsms.api.template.SendTempSMSResult; 17 | import cn.jsms.api.template.TempSMSResult; 18 | import cn.jsms.api.template.TemplatePayload; 19 | import org.junit.Before; 20 | import org.junit.Test; 21 | import org.junit.experimental.categories.Category; 22 | import org.slf4j.Logger; 23 | import org.slf4j.LoggerFactory; 24 | 25 | import com.google.gson.JsonObject; 26 | 27 | import cn.jiguang.common.resp.APIConnectionException; 28 | import cn.jiguang.common.resp.APIRequestException; 29 | import cn.jsms.api.BaseTest; 30 | import cn.jsms.api.SendSMSResult; 31 | import cn.jsms.api.SlowTests; 32 | import cn.jsms.api.ValidSMSResult; 33 | import cn.jsms.api.common.SMSClient; 34 | import cn.jsms.api.common.model.SMSPayload; 35 | 36 | import java.io.File; 37 | import java.util.ArrayList; 38 | import java.util.HashMap; 39 | import java.util.List; 40 | import java.util.Map; 41 | 42 | 43 | @Category(SlowTests.class) 44 | public class SMSClientTest extends BaseTest { 45 | private static final String appkey = "09198ca47f1cc830aa3e064c"; 46 | private static final String masterSecret = "4258ba884dbbceefe3cdb737"; 47 | private static Logger LOG = LoggerFactory.getLogger(SMSClientTest.class); 48 | private SMSClient client = null; 49 | 50 | @Before 51 | public void before() throws Exception { 52 | client = new SMSClient(MASTER_SECRET, APP_KEY); 53 | } 54 | 55 | @Test 56 | public void testSendSMSCode() { 57 | SMSPayload payload = SMSPayload.newBuilder() 58 | .setMobileNumber("13800138000") 59 | .setTempId(1) 60 | // .setSignId(1380) 61 | .build(); 62 | 63 | JsonObject json = new JsonObject(); 64 | json.addProperty("mobile", "13800138000"); 65 | json.addProperty("temp_id", 1); 66 | 67 | assertEquals(payload.toJSON(), json); 68 | 69 | try { 70 | SendSMSResult res = client.sendSMSCode(payload); 71 | assertTrue(res.isResultOK()); 72 | LOG.info(res.toString()); 73 | } catch (APIConnectionException e) { 74 | LOG.error("Connection error. Should retry later. ", e); 75 | } catch (APIRequestException e) { 76 | LOG.error("Error response from JPush server. Should review and fix it. ", e); 77 | LOG.info("HTTP Status: " + e.getStatus()); 78 | LOG.info("Error Message: " + e.getMessage()); 79 | } 80 | 81 | } 82 | 83 | @Test(expected = IllegalArgumentException.class) 84 | public void testSendSMSCode_MobileNull() { 85 | SMSPayload payload = SMSPayload.newBuilder() 86 | .setTempId(1) 87 | .build(); 88 | 89 | JsonObject json = new JsonObject(); 90 | json.addProperty("temp_id", 1); 91 | 92 | assertEquals(payload.toJSON(), json); 93 | } 94 | 95 | @Test(expected = IllegalArgumentException.class) 96 | public void testSendSMSCode_MobileEmpty() { 97 | SMSPayload payload = SMSPayload.newBuilder() 98 | .setMobileNumber("") 99 | .setTempId(1) 100 | .build(); 101 | 102 | JsonObject json = new JsonObject(); 103 | json.addProperty("mobile", ""); 104 | json.addProperty("temp_id", 1); 105 | 106 | assertEquals(payload.toJSON(), json); 107 | } 108 | 109 | @Test(expected = IllegalArgumentException.class) 110 | public void testSendSMSCode_TempIdNegative() { 111 | SMSPayload payload = SMSPayload.newBuilder() 112 | .setMobileNumber("13800138000") 113 | .setTempId(-1) 114 | .build(); 115 | 116 | JsonObject json = new JsonObject(); 117 | json.addProperty("mobile", "13800138000"); 118 | json.addProperty("temp_id", -1); 119 | 120 | assertEquals(payload.toJSON(), json); 121 | } 122 | 123 | @Test 124 | public void testSendValidSMSCode() { 125 | try { 126 | ValidSMSResult res = client.sendValidSMSCode("f3247cce-811c-4260-9bc6-ed27e2e81963", "865425"); 127 | assertEquals(true, res.getIsValid()); 128 | LOG.info(res.toString()); 129 | } catch (APIConnectionException e) { 130 | LOG.error("Connection error. Should retry later. ", e); 131 | } catch (APIRequestException e) { 132 | LOG.error("Error response from JPush server. Should review and fix it. ", e); 133 | LOG.info("HTTP Status: " + e.getStatus()); 134 | LOG.info("Error Message: " + e.getMessage()); 135 | } 136 | } 137 | 138 | @Test(expected = IllegalArgumentException.class) 139 | public void testSendValidSMSCode_InvalidCode1() { 140 | try { 141 | client.sendValidSMSCode("5d7f4f78-5f41-4025-a253-50bc9a3ae1d6", "-1"); 142 | } catch (APIConnectionException e) { 143 | LOG.error("Connection error. Should retry later. ", e); 144 | } catch (APIRequestException e) { 145 | LOG.error("Error response from JPush server. Should review and fix it. ", e); 146 | LOG.info("HTTP Status: " + e.getStatus()); 147 | LOG.info("Error Message: " + e.getMessage()); 148 | } 149 | } 150 | 151 | @Test(expected = IllegalArgumentException.class) 152 | public void testSendValidSMSCode_InvalidCode2() { 153 | try { 154 | client.sendValidSMSCode("5d7f4f78-5f41-4025-a253-50bc9a3ae1d6", "123"); 155 | } catch (APIConnectionException e) { 156 | LOG.error("Connection error. Should retry later. ", e); 157 | } catch (APIRequestException e) { 158 | LOG.error("Error response from JPush server. Should review and fix it. ", e); 159 | LOG.info("HTTP Status: " + e.getStatus()); 160 | LOG.info("Error Message: " + e.getMessage()); 161 | } 162 | } 163 | 164 | @Test(expected = IllegalArgumentException.class) 165 | public void testSendValidSMSCode_InvalidCode3() { 166 | try { 167 | client.sendValidSMSCode("5d7f4f78-5f41-4025-a253-50bc9a3ae1d6", "1234567"); 168 | } catch (APIConnectionException e) { 169 | LOG.error("Connection error. Should retry later. ", e); 170 | } catch (APIRequestException e) { 171 | LOG.error("Error response from JPush server. Should review and fix it. ", e); 172 | LOG.info("HTTP Status: " + e.getStatus()); 173 | LOG.info("Error Message: " + e.getMessage()); 174 | } 175 | } 176 | 177 | @Test 178 | public void testSendVoiceSMSCode() { 179 | SMSPayload payload = SMSPayload.newBuilder() 180 | .setMobileNumber("13800138000") 181 | .setVoiceLang(2) 182 | .setCode("039482") 183 | .build(); 184 | 185 | JsonObject json = new JsonObject(); 186 | json.addProperty("mobile", "13800138000"); 187 | json.addProperty("voice_lang", 2); 188 | json.addProperty("code", "039482"); 189 | assertEquals(payload.toJSON(), json); 190 | 191 | try { 192 | SendSMSResult res = client.sendVoiceSMSCode(payload); 193 | LOG.info(res.toString()); 194 | } catch (APIRequestException e) { 195 | LOG.error("Error response from JPush server. Should review and fix it. ", e); 196 | LOG.info("HTTP Status: " + e.getStatus()); 197 | LOG.info("Error Message: " + e.getMessage()); 198 | } catch (APIConnectionException e) { 199 | LOG.error("Connection error. Should retry later. ", e); 200 | } 201 | } 202 | 203 | @Test 204 | public void testSendTempSMS() { 205 | SMSPayload payload = SMSPayload.newBuilder() 206 | .setMobileNumber("13800138000") 207 | .setTempId(5118) 208 | // .setSignId(1380) 209 | .addTempPara("test", "jpush") 210 | .build(); 211 | 212 | JsonObject json = new JsonObject(); 213 | json.addProperty("mobile", "13800138000"); 214 | json.addProperty("temp_id", 5118); 215 | JsonObject tempJson = new JsonObject(); 216 | tempJson.addProperty("test", "jpush"); 217 | json.add("temp_para", tempJson); 218 | assertEquals(payload.toJSON(), json); 219 | 220 | try { 221 | SendSMSResult res = client.sendTemplateSMS(payload); 222 | assertTrue(res.isResultOK()); 223 | LOG.info(res.toString()); 224 | } catch (APIConnectionException e) { 225 | LOG.error("Connection error. Should retry later. ", e); 226 | } catch (APIRequestException e) { 227 | LOG.error("Error response from JPush server. Should review and fix it. ", e); 228 | LOG.info("HTTP Status: " + e.getStatus()); 229 | LOG.info("Error Message: " + e.getMessage()); 230 | } 231 | } 232 | 233 | @Test 234 | public void testSendTempSMS_withMap() { 235 | Map test = new HashMap(); 236 | test.put("test", "jpush"); 237 | SMSPayload payload = SMSPayload.newBuilder() 238 | .setMobileNumber("13800138000") 239 | .setTempId(5118) 240 | .setTempPara(test) 241 | .build(); 242 | 243 | JsonObject json = new JsonObject(); 244 | json.addProperty("mobile", "13800138000"); 245 | json.addProperty("temp_id", 5118); 246 | JsonObject tempJson = new JsonObject(); 247 | tempJson.addProperty("test", "jpush"); 248 | json.add("temp_para", tempJson); 249 | assertEquals(payload.toJSON(), json); 250 | 251 | try { 252 | SendSMSResult res = client.sendTemplateSMS(payload); 253 | assertTrue(res.isResultOK()); 254 | LOG.info(res.toString()); 255 | } catch (APIConnectionException e) { 256 | LOG.error("Connection error. Should retry later. ", e); 257 | } catch (APIRequestException e) { 258 | LOG.error("Error response from JPush server. Should review and fix it. ", e); 259 | LOG.info("HTTP Status: " + e.getStatus()); 260 | LOG.info("Error Message: " + e.getMessage()); 261 | } 262 | } 263 | 264 | @Test 265 | public void testSendTempSMS_tempParaNull() { 266 | SMSPayload payload = SMSPayload.newBuilder() 267 | .setMobileNumber("13800138000") 268 | .setTempId(5118) 269 | .build(); 270 | try { 271 | SendSMSResult res = client.sendTemplateSMS(payload); 272 | assertTrue(res.getResponseCode() == 403); 273 | LOG.info(res.toString()); 274 | } catch (APIConnectionException e) { 275 | LOG.error("Connection error. Should retry later. ", e); 276 | } catch (APIRequestException e) { 277 | LOG.error("Error response from JPush server. Should review and fix it. ", e); 278 | LOG.info("HTTP Status: " + e.getStatus()); 279 | LOG.info("Error Message: " + e.getMessage()); 280 | } 281 | } 282 | 283 | @Test 284 | public void testSendBatchTemplateSMS() { 285 | List list = new ArrayList(); 286 | RecipientPayload recipientPayload1 = new RecipientPayload.Builder() 287 | .setMobile("13800138000") 288 | .addTempPara("code", "638938") 289 | .build(); 290 | RecipientPayload recipientPayload2 = new RecipientPayload.Builder() 291 | .setMobile("13800138000") 292 | .addTempPara("code", "829302") 293 | .build(); 294 | list.add(recipientPayload1); 295 | list.add(recipientPayload2); 296 | RecipientPayload[] recipientPayloads = new RecipientPayload[list.size()]; 297 | BatchSMSPayload smsPayload = BatchSMSPayload.newBuilder() 298 | .setTempId(1) 299 | // .setSignId(1380) 300 | .setRecipients(list.toArray(recipientPayloads)) 301 | .build(); 302 | try { 303 | BatchSMSResult result = client.sendBatchTemplateSMS(smsPayload); 304 | LOG.info("Got result: " + result); 305 | } catch (APIConnectionException e) { 306 | LOG.error("Connection error. Should retry later. ", e); 307 | } catch (APIRequestException e) { 308 | LOG.error("Error response from JPush server. Should review and fix it. ", e); 309 | LOG.info("HTTP Status: " + e.getStatus()); 310 | LOG.info("Error Message: " + e.getMessage()); 311 | } 312 | } 313 | 314 | @Test 315 | public void testSendScheduleSMS() { 316 | ScheduleSMSPayload payload = ScheduleSMSPayload.newBuilder() 317 | .setMobileNumber("13800138000") 318 | .setTempId(1) 319 | .setSendTime("2017-08-02 14:12:00") 320 | .addTempPara("code", "798560") 321 | .build(); 322 | try { 323 | ScheduleResult result = client.sendScheduleSMS(payload); 324 | LOG.info(result.toString()); 325 | } catch (APIConnectionException e) { 326 | LOG.error("Connection error. Should retry later. ", e); 327 | } catch (APIRequestException e) { 328 | LOG.error("Error response from JPush server. Should review and fix it. ", e); 329 | LOG.info("HTTP Status: " + e.getStatus()); 330 | LOG.info("Error Message: " + e.getMessage()); 331 | } 332 | } 333 | 334 | @Test 335 | public void testUpdateScheduleSMS() { 336 | ScheduleSMSPayload payload = ScheduleSMSPayload.newBuilder() 337 | .setMobileNumber("13800138000") 338 | .setTempId(1) 339 | .setSendTime("2017-08-02 14:13:00") 340 | .addTempPara("code", "110110") 341 | .build(); 342 | try { 343 | ScheduleResult result = client.updateScheduleSMS(payload, "91b81a48-49f6-4eb9-a95f-020f88adcfba"); 344 | LOG.info(result.toString()); 345 | } catch (APIConnectionException e) { 346 | LOG.error("Connection error. Should retry later. ", e); 347 | } catch (APIRequestException e) { 348 | LOG.error("Error response from JPush server. Should review and fix it. ", e); 349 | LOG.info("HTTP Status: " + e.getStatus()); 350 | LOG.info("Error Message: " + e.getMessage()); 351 | } 352 | } 353 | 354 | @Test 355 | public void testSendBatchScheduleSMS() { 356 | List list = new ArrayList(); 357 | RecipientPayload recipientPayload1 = new RecipientPayload.Builder() 358 | .setMobile("13800138000") 359 | .addTempPara("code", "638938") 360 | .build(); 361 | RecipientPayload recipientPayload2 = new RecipientPayload.Builder() 362 | .setMobile("13800138000") 363 | .addTempPara("code", "829302") 364 | .build(); 365 | list.add(recipientPayload1); 366 | list.add(recipientPayload2); 367 | RecipientPayload[] recipientPayloads = new RecipientPayload[list.size()]; 368 | ScheduleSMSPayload smsPayload = ScheduleSMSPayload.newBuilder() 369 | .setSendTime("2017-08-02 14:20:00") 370 | .setTempId(1) 371 | .setRecipients(list.toArray(recipientPayloads)) 372 | .build(); 373 | try { 374 | BatchSMSResult result = client.sendBatchScheduleSMS(smsPayload); 375 | LOG.info(result.toString()); 376 | } catch (APIConnectionException e) { 377 | LOG.error("Connection error. Should retry later. ", e); 378 | } catch (APIRequestException e) { 379 | LOG.error("Error response from JPush server. Should review and fix it. ", e); 380 | LOG.info("HTTP Status: " + e.getStatus()); 381 | LOG.info("Error Message: " + e.getMessage()); 382 | } 383 | } 384 | 385 | @Test 386 | public void testUpdateBatchScheduleSMS() { 387 | List list = new ArrayList(); 388 | RecipientPayload recipientPayload1 = new RecipientPayload.Builder() 389 | .setMobile("13800138000") 390 | .addTempPara("code", "328393") 391 | .build(); 392 | RecipientPayload recipientPayload2 = new RecipientPayload.Builder() 393 | .setMobile("13800138000") 394 | .addTempPara("code", "489042") 395 | .build(); 396 | list.add(recipientPayload1); 397 | list.add(recipientPayload2); 398 | RecipientPayload[] recipientPayloads = new RecipientPayload[list.size()]; 399 | ScheduleSMSPayload smsPayload = ScheduleSMSPayload.newBuilder() 400 | .setSendTime("2017-08-01 14:20:00") 401 | .setTempId(1) 402 | .setRecipients(list.toArray(recipientPayloads)) 403 | .build(); 404 | try { 405 | BatchSMSResult result = client.updateBatchScheduleSMS(smsPayload, "d2afae04-6211-4c51-b51a-bbfbf5576f03"); 406 | LOG.info(result.toString()); 407 | } catch (APIConnectionException e) { 408 | LOG.error("Connection error. Should retry later. ", e); 409 | } catch (APIRequestException e) { 410 | LOG.error("Error response from JPush server. Should review and fix it. ", e); 411 | LOG.info("HTTP Status: " + e.getStatus()); 412 | LOG.info("Error Message: " + e.getMessage()); 413 | } 414 | } 415 | 416 | @Test 417 | public void testDeleteScheduleSMS() { 418 | try { 419 | ResponseWrapper result = client.deleteScheduleSMS("sd"); 420 | LOG.info("Response content: " + result.responseContent + " response code: " + result.responseCode); 421 | } catch (APIConnectionException e) { 422 | LOG.error("Connection error. Should retry later. ", e); 423 | } catch (APIRequestException e) { 424 | LOG.error("Error response from JPush server. Should review and fix it. ", e); 425 | LOG.info("HTTP Status: " + e.getStatus()); 426 | LOG.info("Error Message: " + e.getMessage()); 427 | } 428 | } 429 | 430 | @Test 431 | public void testGetAccountSMSBalance() { 432 | try { 433 | client = new SMSClient(DEV_SECRET, DEV_KEY); 434 | AccountBalanceResult result = client.getSMSBalance(); 435 | LOG.info(result.toString()); 436 | } catch (APIConnectionException e) { 437 | LOG.error("Connection error. Should retry later. ", e); 438 | } catch (APIRequestException e) { 439 | LOG.error("Error response from JPush server. Should review and fix it. ", e); 440 | LOG.info("HTTP Status: " + e.getStatus()); 441 | LOG.info("Error Message: " + e.getMessage()); 442 | } 443 | } 444 | 445 | @Test 446 | public void testGetAppSMSBalance() { 447 | try { 448 | client = new SMSClient(MASTER_SECRET, APP_KEY); 449 | AppBalanceResult result = client.getAppSMSBalance(); 450 | LOG.info(result.toString()); 451 | } catch (APIConnectionException e) { 452 | LOG.error("Connection error. Should retry later. ", e); 453 | } catch (APIRequestException e) { 454 | LOG.error("Error response from JPush server. Should review and fix it. ", e); 455 | LOG.info("HTTP Status: " + e.getStatus()); 456 | LOG.info("Error Message: " + e.getMessage()); 457 | } 458 | } 459 | 460 | @Test 461 | public void testCreateTemplate() { 462 | try { 463 | client = new SMSClient(MASTER_SECRET, APP_KEY); 464 | TemplatePayload payload = TemplatePayload.newBuilder() 465 | .setTemplate("您好,您的验证码是{{code}},2分钟内有效!") 466 | .setType(1) 467 | .setTTL(120) 468 | .setRemark("验证短信") 469 | .build(); 470 | SendTempSMSResult result = client.createTemplate(payload); 471 | LOG.info(result.toString()); 472 | } catch (APIConnectionException e) { 473 | LOG.error("Connection error. Should retry later. ", e); 474 | } catch (APIRequestException e) { 475 | LOG.error("Error response from JPush server. Should review and fix it. ", e); 476 | LOG.info("HTTP Status: " + e.getStatus()); 477 | LOG.info("Error Message: " + e.getMessage()); 478 | } 479 | } 480 | 481 | @Test 482 | public void testUpdateTemplate() { 483 | try { 484 | client = new SMSClient(MASTER_SECRET, APP_KEY); 485 | TemplatePayload payload = TemplatePayload.newBuilder() 486 | .setTempId(12345) 487 | .setTemplate("您好,您的验证码是{{code}},2分钟内有效!") 488 | .setType(1) 489 | .setTTL(120) 490 | .setRemark("验证短信") 491 | .build(); 492 | SendTempSMSResult result = client.updateTemplate(payload, 12345); 493 | LOG.info(result.toString()); 494 | } catch (APIConnectionException e) { 495 | LOG.error("Connection error. Should retry later. ", e); 496 | } catch (APIRequestException e) { 497 | LOG.error("Error response from JPush server. Should review and fix it. ", e); 498 | LOG.info("HTTP Status: " + e.getStatus()); 499 | LOG.info("Error Message: " + e.getMessage()); 500 | } 501 | } 502 | 503 | @Test 504 | public void testCheckTemplate() { 505 | try { 506 | client = new SMSClient(MASTER_SECRET, APP_KEY); 507 | TempSMSResult result = client.checkTemplate(144923); 508 | LOG.info(result.toString()); 509 | } catch (APIConnectionException e) { 510 | LOG.error("Connection error. Should retry later. ", e); 511 | } catch (APIRequestException e) { 512 | LOG.error("Error response from JPush server. Should review and fix it. ", e); 513 | LOG.info("HTTP Status: " + e.getStatus()); 514 | LOG.info("Error Message: " + e.getMessage()); 515 | } 516 | } 517 | 518 | @Test 519 | public void testDeleteTemplate() { 520 | try { 521 | client = new SMSClient(MASTER_SECRET, APP_KEY); 522 | ResponseWrapper result = client.deleteTemplate(144923); 523 | LOG.info(result.toString()); 524 | } catch (APIConnectionException e) { 525 | LOG.error("Connection error. Should retry later. ", e); 526 | } catch (APIRequestException e) { 527 | LOG.error("Error response from JPush server. Should review and fix it. ", e); 528 | LOG.info("HTTP Status: " + e.getStatus()); 529 | LOG.info("Error Message: " + e.getMessage()); 530 | } 531 | } 532 | @Test 533 | public void testUpdateSign(){ 534 | try { 535 | File avatar_file = new File("C:\\Users\\jiguang\\Desktop\\testSign.jpg"); 536 | File[] files = new File[1]; 537 | files[0] = avatar_file; 538 | SMSClient client = new SMSClient(masterSecret, appkey); 539 | SignPayload payload = SignPayload.newBuilder(). 540 | sign("SDK6"). 541 | type(1). 542 | remark("SDK测试"). 543 | images(files). 544 | build(); 545 | SignResult result = client.updateSign(payload,10859); 546 | LOG.info(result.toString()); 547 | }catch (APIConnectionException e) { 548 | LOG.error("Connection error. Should retry later. ", e); 549 | } catch (APIRequestException e) { 550 | LOG.error("Error response from JPush server. Should review and fix it. ", e); 551 | LOG.info("HTTP Status: " + e.getStatus()); 552 | LOG.info("Error Message: " + e.getMessage()); 553 | } 554 | } 555 | 556 | } 557 | -------------------------------------------------------------------------------- /src/main/java/cn/jsms/api/common/SMSClient.java: -------------------------------------------------------------------------------- 1 | package cn.jsms.api.common; 2 | 3 | import java.io.*; 4 | import java.net.HttpURLConnection; 5 | import java.net.MalformedURLException; 6 | import java.net.ProtocolException; 7 | import java.net.URL; 8 | import java.util.HashMap; 9 | import java.util.Iterator; 10 | import java.util.Map; 11 | import java.util.regex.Pattern; 12 | 13 | import cn.jiguang.common.connection.IHttpClient; 14 | import cn.jiguang.common.connection.NettyHttpClient; 15 | import cn.jiguang.common.utils.StringUtils; 16 | import cn.jsms.api.account.AccountBalanceResult; 17 | import cn.jsms.api.account.AppBalanceResult; 18 | import cn.jsms.api.common.model.BatchSMSPayload; 19 | import cn.jsms.api.common.model.BatchSMSResult; 20 | import cn.jsms.api.schedule.model.ScheduleResult; 21 | import cn.jsms.api.schedule.model.ScheduleSMSPayload; 22 | import cn.jsms.api.schedule.model.ScheduleSMSResult; 23 | import cn.jsms.api.sign.DefaultSignPayload; 24 | import cn.jsms.api.sign.SignInfoResult; 25 | import cn.jsms.api.sign.SignPayload; 26 | import cn.jsms.api.sign.SignResult; 27 | import cn.jsms.api.template.SendTempSMSResult; 28 | import cn.jsms.api.template.TempSMSResult; 29 | import cn.jsms.api.template.TemplatePayload; 30 | import com.google.gson.JsonObject; 31 | 32 | import cn.jiguang.common.ServiceHelper; 33 | import cn.jiguang.common.utils.Preconditions; 34 | import cn.jiguang.common.connection.HttpProxy; 35 | import cn.jiguang.common.connection.NativeHttpClient; 36 | import cn.jiguang.common.resp.APIConnectionException; 37 | import cn.jiguang.common.resp.APIRequestException; 38 | import cn.jiguang.common.resp.ResponseWrapper; 39 | import cn.jsms.api.SendSMSResult; 40 | import cn.jsms.api.ValidSMSResult; 41 | import cn.jsms.api.common.model.SMSPayload; 42 | import org.slf4j.Logger; 43 | import org.slf4j.LoggerFactory; 44 | 45 | import javax.net.ssl.SSLException; 46 | 47 | public class SMSClient { 48 | 49 | private static String SMS_CODE = "code"; 50 | private final String BOUNDARY = "========7d4a6d158c9"; 51 | 52 | private String _baseUrl; 53 | private String _smsCodePath; 54 | private String _validPath; 55 | private String _voiceCodePath; 56 | private String _shortMsgPath; 57 | private String _schedulePath; 58 | private String _signPath; 59 | private String _signDefaultPath; 60 | private String _accountPath; 61 | private String _tempMsgPath; 62 | private IHttpClient _httpClient; 63 | private String _authCode; 64 | 65 | public SMSClient(String masterSecret, String appkey) { 66 | this(masterSecret, appkey, null, JSMSConfig.getInstance()); 67 | } 68 | 69 | public SMSClient(String masterSecret, String appkey, HttpProxy proxy, JSMSConfig conf) { 70 | ServiceHelper.checkBasic(appkey, masterSecret); 71 | 72 | _baseUrl = (String) conf.get(JSMSConfig.API_HOST_NAME); 73 | _smsCodePath = (String) conf.get(JSMSConfig.CODE_PATH); 74 | _validPath = (String) conf.get(JSMSConfig.VALID_PATH); 75 | _voiceCodePath = (String) conf.get(JSMSConfig.VOICE_CODE_PATH); 76 | _shortMsgPath = (String) conf.get(JSMSConfig.SHORT_MESSAGE_PATH); 77 | _tempMsgPath = (String) conf.get(JSMSConfig.TEMPlATE_MESSAGE_PATH); 78 | _signPath = (String) conf.get(JSMSConfig.SIGN_PATH); 79 | _signDefaultPath = (String) conf.get(JSMSConfig.SIGN_DEFAULT_PATH); 80 | _schedulePath = (String) conf.get(JSMSConfig.SCHEDULE_PATH); 81 | _accountPath = (String) conf.get(JSMSConfig.ACCOUNT_PATH); 82 | String authCode = ServiceHelper.getBasicAuthorization(appkey, masterSecret); 83 | _authCode = authCode; 84 | this._httpClient = new NativeHttpClient(authCode, proxy, conf.getClientConfig()); 85 | } 86 | 87 | /** 88 | * Send SMS verification code to mobile 89 | * 90 | * @param payload include two parameters: mobile number and templete id. The second parameter is optional. 91 | * @return return SendSMSResult which includes msg_id 92 | * @throws APIConnectionException connection exception 93 | * @throws APIRequestException request exception 94 | */ 95 | public SendSMSResult sendSMSCode(SMSPayload payload) 96 | throws APIConnectionException, APIRequestException { 97 | Preconditions.checkArgument(null != payload, "SMS payload should not be null"); 98 | 99 | ResponseWrapper response = _httpClient.sendPost(_baseUrl + _smsCodePath, payload.toString()); 100 | return SendSMSResult.fromResponse(response, SendSMSResult.class); 101 | } 102 | 103 | /** 104 | * Send SMS verification code to server, to verify if the code valid 105 | * 106 | * @param msgId The message id of the verification code 107 | * @param code Verification code 108 | * @return return ValidSMSResult includes is_valid 109 | * @throws APIConnectionException connection exception 110 | * @throws APIRequestException request exception 111 | */ 112 | public ValidSMSResult sendValidSMSCode(String msgId, String code) 113 | throws APIConnectionException, APIRequestException { 114 | Preconditions.checkArgument(null != msgId, "Message id should not be null"); 115 | Pattern codePattern = Pattern.compile("^[0-9]{6}"); 116 | Preconditions.checkArgument(codePattern.matcher(code).matches(), "The verification code shoude be consist of six number"); 117 | JsonObject json = new JsonObject(); 118 | json.addProperty(SMS_CODE, code); 119 | 120 | ResponseWrapper response = _httpClient.sendPost(_baseUrl + _smsCodePath + "/" + msgId + _validPath, json.toString()); 121 | return ValidSMSResult.fromResponse(response, ValidSMSResult.class); 122 | } 123 | 124 | /** 125 | * Send voice SMS verification code to mobile 126 | * 127 | * @param payload payload includes two parameters: mobile number and ttl(time to live), 128 | * the second one is optional(if miss ttl, will use default value 60 seconds). 129 | * @return return SendSMSResult which includes msg_id 130 | * @throws APIConnectionException connection exception 131 | * @throws APIRequestException request exception 132 | */ 133 | public SendSMSResult sendVoiceSMSCode(SMSPayload payload) 134 | throws APIConnectionException, APIRequestException { 135 | Preconditions.checkArgument(null != payload, "SMS payload should not be null"); 136 | 137 | ResponseWrapper response = _httpClient.sendPost(_baseUrl + _voiceCodePath, payload.toString()); 138 | return SendSMSResult.fromResponse(response, SendSMSResult.class); 139 | } 140 | 141 | /** 142 | * Send template SMS to mobile 143 | * 144 | * @param payload payload includes mobile, temp_id and temp_para, the temp_para is a map, 145 | * which's key is what you had set in jiguang portal 146 | * @return return SendSMSResult which includes msg_id 147 | * @throws APIConnectionException connection exception 148 | * @throws APIRequestException request exception 149 | */ 150 | public SendSMSResult sendTemplateSMS(SMSPayload payload) 151 | throws APIConnectionException, APIRequestException { 152 | Preconditions.checkArgument(null != payload, "SMS payload should not be null"); 153 | 154 | ResponseWrapper response = _httpClient.sendPost(_baseUrl + _shortMsgPath, payload.toString()); 155 | return SendSMSResult.fromResponse(response, SendSMSResult.class); 156 | } 157 | 158 | /** 159 | * Send a batch of template SMS 160 | * 161 | * @param payload BatchSMSPayload 162 | * @return BatchSMSResult 163 | * @throws APIConnectionException connect exception 164 | * @throws APIRequestException request exception 165 | */ 166 | public BatchSMSResult sendBatchTemplateSMS(BatchSMSPayload payload) 167 | throws APIConnectionException, APIRequestException { 168 | Preconditions.checkArgument(null != payload, "BatchSMSPayload should not be null"); 169 | ResponseWrapper responseWrapper = _httpClient.sendPost(_baseUrl + _shortMsgPath + "/batch", payload.toString()); 170 | return BatchSMSResult.fromResponse(responseWrapper, BatchSMSResult.class); 171 | } 172 | 173 | public void setHttpClient(IHttpClient client) { 174 | this._httpClient = client; 175 | } 176 | 177 | // 如果使用 NettyHttpClient,在发送请求后需要手动调用 close 方法 178 | public void close() { 179 | if (_httpClient != null && _httpClient instanceof NettyHttpClient) { 180 | ((NettyHttpClient) _httpClient).close(); 181 | } 182 | } 183 | 184 | /** 185 | * Submit a mission that sending a template SMS with pointed schedule 186 | * 187 | * @param payload ScheduleSMSPayload 188 | * @return ScheduleResult which includes schedule_id 189 | * @throws APIConnectionException connect exception 190 | * @throws APIRequestException request exception 191 | */ 192 | public ScheduleResult sendScheduleSMS(ScheduleSMSPayload payload) throws APIConnectionException, APIRequestException { 193 | Preconditions.checkArgument(null != payload, "Schedule SMS payload should not be null"); 194 | Preconditions.checkArgument(null != payload.getMobile(), "Mobile should not be null"); 195 | Preconditions.checkArgument(StringUtils.isMobileNumber(payload.getMobile()), "Invalid mobile number"); 196 | ResponseWrapper responseWrapper = _httpClient.sendPost(_baseUrl + _schedulePath, payload.toString()); 197 | return ScheduleResult.fromResponse(responseWrapper, ScheduleResult.class); 198 | } 199 | 200 | /** 201 | * Modify SMS with schedule 202 | * 203 | * @param payload ScheduleSMSPayload 204 | * @param scheduleId id 205 | * @return ScheduleResult which includes schedule_id 206 | * @throws APIConnectionException connect exception 207 | * @throws APIRequestException request exception 208 | */ 209 | public ScheduleResult updateScheduleSMS(ScheduleSMSPayload payload, String scheduleId) 210 | throws APIConnectionException, APIRequestException { 211 | Preconditions.checkArgument(null != payload, "Schedule SMS payload should not be null"); 212 | Preconditions.checkArgument(null != scheduleId, "Schedule id should not be null"); 213 | Preconditions.checkArgument(null != payload.getMobile(), "Mobile should not be null"); 214 | Preconditions.checkArgument(StringUtils.isMobileNumber(payload.getMobile()), "Invalid mobile number"); 215 | ResponseWrapper responseWrapper = _httpClient.sendPut(_baseUrl + _schedulePath + "/" + scheduleId, payload.toString()); 216 | return ScheduleResult.fromResponse(responseWrapper, ScheduleResult.class); 217 | } 218 | 219 | /** 220 | * Submit a mission that sending a batch of SMS with schedule 221 | * 222 | * @param payload Payload should include sendTime and recipients 223 | * @return BatchSMSResult 224 | * @throws APIConnectionException connect exception 225 | * @throws APIRequestException request exception 226 | */ 227 | public BatchSMSResult sendBatchScheduleSMS(ScheduleSMSPayload payload) 228 | throws APIConnectionException, APIRequestException { 229 | Preconditions.checkArgument(null != payload, "Schedule SMS payload should not be null"); 230 | Preconditions.checkArgument(null != payload.getRecipients(), "Recipients should not be null"); 231 | ResponseWrapper responseWrapper = _httpClient.sendPost(_baseUrl + _schedulePath + "/batch", payload.toString()); 232 | return BatchSMSResult.fromResponse(responseWrapper, BatchSMSResult.class); 233 | } 234 | 235 | /** 236 | * Update batch of SMS with schedule 237 | * 238 | * @param payload ScheduleSMSPayload 239 | * @param scheduleId id 240 | * @return BatchSMSResult 241 | * @throws APIConnectionException connection exception 242 | * @throws APIRequestException request exception 243 | */ 244 | public BatchSMSResult updateBatchScheduleSMS(ScheduleSMSPayload payload, String scheduleId) 245 | throws APIConnectionException, APIRequestException { 246 | Preconditions.checkArgument(null != payload, "Schedule SMS payload should not be null"); 247 | Preconditions.checkArgument(null != payload.getRecipients(), "Recipients should not be null"); 248 | Preconditions.checkArgument(null != scheduleId, "Schedule id should not be null"); 249 | ResponseWrapper responseWrapper = _httpClient.sendPut(_baseUrl + _schedulePath + "/batch/" + scheduleId, payload.toString()); 250 | return BatchSMSResult.fromResponse(responseWrapper, BatchSMSResult.class); 251 | } 252 | 253 | /** 254 | * Get schedule SMS by scheduleId 255 | * 256 | * @param scheduleId id 257 | * @return ScheduleSMSResult 258 | * @throws APIConnectionException connection exception 259 | * @throws APIRequestException request exception 260 | */ 261 | public ScheduleSMSResult getScheduleSMS(String scheduleId) throws APIConnectionException, APIRequestException { 262 | Preconditions.checkArgument(null != scheduleId, "Schedule id should not be null"); 263 | ResponseWrapper responseWrapper = _httpClient.sendGet(_baseUrl + _schedulePath + "/" + scheduleId); 264 | return ScheduleSMSResult.fromResponse(responseWrapper, ScheduleSMSResult.class); 265 | } 266 | 267 | /** 268 | * Delete schedule SMS by scheduleId 269 | * 270 | * @param scheduleId id 271 | * @return No content 272 | * @throws APIConnectionException connect exception 273 | * @throws APIRequestException request exception 274 | */ 275 | public ResponseWrapper deleteScheduleSMS(String scheduleId) throws APIConnectionException, APIRequestException { 276 | Preconditions.checkArgument(null != scheduleId, "Schedule id should not be null"); 277 | return _httpClient.sendDelete(_baseUrl + _schedulePath + "/" + scheduleId); 278 | } 279 | 280 | /** 281 | * Get account's SMS balance 282 | * 283 | * @return AccountBalanceResult 284 | * @throws APIConnectionException connect exception 285 | * @throws APIRequestException request exception 286 | */ 287 | public AccountBalanceResult getSMSBalance() throws APIConnectionException, APIRequestException { 288 | ResponseWrapper responseWrapper = _httpClient.sendGet(_baseUrl + _accountPath + "/dev"); 289 | return AccountBalanceResult.fromResponse(responseWrapper, AccountBalanceResult.class); 290 | } 291 | 292 | /** 293 | * Get app's SMS balance of an account 294 | * 295 | * @return AppBalanceResult 296 | * @throws APIConnectionException connect exception 297 | * @throws APIRequestException request exception 298 | */ 299 | public AppBalanceResult getAppSMSBalance() throws APIConnectionException, APIRequestException { 300 | ResponseWrapper responseWrapper = _httpClient.sendGet(_baseUrl + _accountPath + "/app"); 301 | return AppBalanceResult.fromResponse(responseWrapper, AppBalanceResult.class); 302 | } 303 | 304 | //=============== Template API ================= 305 | 306 | /** 307 | * Create template sms. 308 | * 309 | * @param payload {@link TemplatePayload } 310 | * @return {@link SendTempSMSResult }, include temp_id 311 | * @throws APIConnectionException connect exception 312 | * @throws APIRequestException request exception 313 | */ 314 | public SendTempSMSResult createTemplate(TemplatePayload payload) throws APIConnectionException, APIRequestException { 315 | Preconditions.checkArgument(null != payload, "Template payload should not be null"); 316 | ResponseWrapper responseWrapper = _httpClient.sendPost(_baseUrl + _tempMsgPath, payload.toString()); 317 | return SendTempSMSResult.fromResponse(responseWrapper, SendTempSMSResult.class); 318 | } 319 | 320 | /** 321 | * update template sms. Template can be modified ONLY when status is not approved 322 | * 323 | * @param payload {@link TemplatePayload } 324 | * @param tempId template id 325 | * @return {@link SendTempSMSResult }, include temp_id 326 | * @throws APIConnectionException connect exception 327 | * @throws APIRequestException request exception 328 | */ 329 | public SendTempSMSResult updateTemplate(TemplatePayload payload, int tempId) throws APIConnectionException, APIRequestException { 330 | Preconditions.checkArgument(null != payload, "Template payload should not be null"); 331 | Preconditions.checkArgument(tempId > 0, "temp id is invalid"); 332 | ResponseWrapper responseWrapper = _httpClient.sendPut(_baseUrl + _tempMsgPath + "/" + tempId, payload.toString()); 333 | return SendTempSMSResult.fromResponse(responseWrapper, SendTempSMSResult.class); 334 | } 335 | 336 | /** 337 | * check template by id 338 | * 339 | * @param tempId necessary 340 | * @return {@link TempSMSResult} 341 | * @throws APIConnectionException connect exception 342 | * @throws APIRequestException request exception 343 | */ 344 | public TempSMSResult checkTemplate(int tempId) throws APIConnectionException, APIRequestException { 345 | Preconditions.checkArgument(tempId > 0, "temp id is invalid"); 346 | ResponseWrapper responseWrapper = _httpClient.sendGet(_baseUrl + _tempMsgPath + "/" + tempId); 347 | return TempSMSResult.fromResponse(responseWrapper, TempSMSResult.class); 348 | } 349 | 350 | /** 351 | * Delete template by id 352 | * 353 | * @param tempId necessary 354 | * @return No content 355 | * @throws APIConnectionException connect exception 356 | * @throws APIRequestException request exception 357 | */ 358 | public ResponseWrapper deleteTemplate(int tempId) throws APIConnectionException, APIRequestException { 359 | Preconditions.checkArgument(tempId > 0, "temp id is invalid"); 360 | return _httpClient.sendDelete(_baseUrl + _tempMsgPath + "/" + tempId); 361 | } 362 | 363 | /** 364 | * create sign 365 | * 其实两个接口可以合并 但没时间搞 366 | * 367 | * @param payload {@link SignPayload } 368 | * @return SignResult 369 | * @throws APIConnectionException connect exception 370 | * @throws APIRequestException request exception 371 | */ 372 | public SignResult createSign(SignPayload payload) throws APIConnectionException, APIRequestException { 373 | Preconditions.checkArgument(null != payload, "sign payload should not be null"); 374 | Preconditions.checkArgument(payload.getType() > 0 && payload.getType() <= 7, 375 | "type should be between 1 and 7"); 376 | Map params = new HashMap(); 377 | params.put(SignPayload.getSIGN(), payload.getSign()); 378 | if (!StringUtils.isEmpty(payload.getRemark())) { 379 | Preconditions.checkArgument(payload.getRemark().length() <= 100, 380 | "remark too long"); 381 | params.put(SignPayload.getREMARK(), payload.getRemark()); 382 | } 383 | params.put(SignPayload.getTYPE(), payload.getType()); 384 | Map fileParams = new HashMap(); 385 | File[] images = payload.getImages(); 386 | if (images != null && images.length > 0) { 387 | for (File file : payload.getImages()) { 388 | fileParams.put(file.getName(), getBytes(file)); 389 | } 390 | } 391 | String url = _baseUrl + _signPath; 392 | try { 393 | ResponseWrapper wrapper = doPostSign(url, params, fileParams, SignPayload.getIMAGES()); 394 | if (wrapper.responseCode != 200) { 395 | throw new APIRequestException(wrapper); 396 | } 397 | return SignResult.fromResponse(wrapper, SignResult.class); 398 | } catch (IOException e) { 399 | e.printStackTrace(); 400 | throw new IllegalArgumentException("fail to creat sign"); 401 | } 402 | } 403 | 404 | /** 405 | * update sign 406 | * 407 | * @param payload {@link SignPayload } 408 | * @param signId necessary 409 | * @return SignResult 410 | * @throws APIConnectionException connect exception 411 | * @throws APIRequestException request exception 412 | */ 413 | public SignResult updateSign(SignPayload payload, int signId) throws APIConnectionException, APIRequestException { 414 | Preconditions.checkArgument(null != payload, "sign payload should not be null"); 415 | Preconditions.checkArgument(payload.getType() > 0 && payload.getType() <= 7, 416 | "type should be between 1 and 7"); 417 | 418 | Map params = new HashMap(); 419 | params.put(SignPayload.getSIGN(), payload.getSign()); 420 | if (!StringUtils.isEmpty(payload.getRemark())) { 421 | Preconditions.checkArgument(payload.getRemark().length() <= 100, 422 | "remark too long"); 423 | params.put(SignPayload.getREMARK(), payload.getRemark()); 424 | } 425 | params.put(SignPayload.getTYPE(), payload.getType()); 426 | Map fileParams = new HashMap(); 427 | File[] images = payload.getImages(); 428 | if (images != null && images.length > 0) { 429 | for (File file : payload.getImages()) { 430 | fileParams.put(file.getName(), getBytes(file)); 431 | } 432 | } 433 | String url = _baseUrl + _signPath + "/" + signId; 434 | try { 435 | ResponseWrapper wrapper = doPostSign(url, params, fileParams, SignPayload.getIMAGES()); 436 | if (wrapper.responseCode != 200) { 437 | throw new APIRequestException(wrapper); 438 | } 439 | return SignResult.fromResponse(wrapper, SignResult.class); 440 | } catch (IOException e) { 441 | e.printStackTrace(); 442 | throw new IllegalArgumentException("fail to update sign"); 443 | } 444 | } 445 | 446 | /** 447 | * delete sig by id 448 | * 449 | * @param signId necessary 450 | * @return ResponseWrapper 451 | * @throws APIConnectionException connect exception 452 | * @throws APIRequestException request exception 453 | */ 454 | public ResponseWrapper deleteSign(int signId) throws APIConnectionException, APIRequestException { 455 | Preconditions.checkArgument(signId > 0, "sign id is invalid"); 456 | return _httpClient.sendDelete(_baseUrl + _signPath + "/" + signId); 457 | } 458 | 459 | /** 460 | * get sign by id 461 | * 462 | * @param signId necessary 463 | * @return SignInfoResult 464 | * @throws APIConnectionException connect exception 465 | * @throws APIRequestException request exception 466 | */ 467 | public SignInfoResult checkSign(int signId) throws APIConnectionException, APIRequestException { 468 | Preconditions.checkArgument(signId > 0, "sign id is invalid"); 469 | ResponseWrapper responseWrapper = _httpClient.sendGet(_baseUrl + _signPath + "/" + signId); 470 | return SignInfoResult.fromResponse(responseWrapper, SignInfoResult.class); 471 | } 472 | 473 | // /** 474 | // * set default sign Discard 475 | // * 476 | // * @param payload 477 | // * @return 478 | // * @throws APIConnectionException 479 | // * @throws APIRequestException 480 | // */ 481 | // public ResponseWrapper setDefaultSign(DefaultSignPayload payload) throws APIConnectionException, APIRequestException { 482 | // Preconditions.checkArgument(payload != null, "sign should not be null"); 483 | // ResponseWrapper responseWrapper = _httpClient.sendPost(_baseUrl + _signDefaultPath, payload.toString()); 484 | // return responseWrapper; 485 | // } 486 | 487 | /** 488 | * post sign 489 | * 490 | * @param strUrl url 491 | * @param params param 492 | * @param fileParams fileParam 493 | * @param fileName fileName 494 | * @return ResponseWrapper 495 | * @throws IOException connect exception 496 | */ 497 | public ResponseWrapper doPostSign(String strUrl, Map params, Map fileParams, String fileName) throws IOException { 499 | ResponseWrapper wrapper = new ResponseWrapper(); 500 | String TWO_HYPHENS = "--"; 501 | String LINE_END = "\r\n"; 502 | 503 | URL url = new URL(strUrl); 504 | HttpURLConnection connection = (HttpURLConnection) url.openConnection();//得到connection对象 505 | /************************************设置请求头*************************************************/ 506 | connection.setRequestMethod("POST"); //设置请求方式为POST 507 | connection.setDoOutput(true); //允许写出 508 | connection.setDoInput(true); //允许读入 509 | connection.setUseCaches(false); //不使用缓存 510 | connection.setRequestProperty("Charset", "utf-8");//编码格式 511 | connection.setRequestProperty("Authorization", _authCode); 512 | connection.setRequestProperty("Content-Type", "multipart/form-data ; boundary=" + BOUNDARY); // 设置发送数据的格式(form-data格式) //boundary为头部分隔符,头部拼接时需要分隔符。例如下面的有多个"Content-Disposition"拼接时需要用到此分隔符 513 | connection.connect(); //连接 514 | /************************************输出流,写数据,start*************************************************/ 515 | DataOutputStream out = new DataOutputStream(connection.getOutputStream());//获得输出流对象 516 | StringBuffer strBufparam = new StringBuffer(); 517 | Iterator it = params.entrySet().iterator(); 518 | while (it.hasNext()) { 519 | //封装键值对数据 520 | Map.Entry entry = (Map.Entry) it.next(); 521 | String key = entry.getKey(); 522 | String value = String.valueOf(entry.getValue()); 523 | 524 | strBufparam.append(TWO_HYPHENS); 525 | strBufparam.append(BOUNDARY); 526 | strBufparam.append(LINE_END);//"--" + BOUNDARY + "\r\n" 527 | strBufparam.append("Content-Disposition: form-data; name=\"" + key + "\""); 528 | strBufparam.append(LINE_END); 529 | strBufparam.append(LINE_END); 530 | strBufparam.append(value); 531 | strBufparam.append(LINE_END); 532 | } 533 | out.write(strBufparam.toString().getBytes("utf-8")); 534 | //写入图片参数 535 | if (fileParams != null && fileParams.size() > 0) { 536 | Iterator fileIt = fileParams.entrySet().iterator(); 537 | while (fileIt.hasNext()) { 538 | Map.Entry fileEntry = (Map.Entry) fileIt.next(); 539 | //拼接文件的参数 540 | StringBuffer strBufFile = new StringBuffer(); 541 | strBufFile.append(TWO_HYPHENS); 542 | strBufFile.append(BOUNDARY); 543 | strBufFile.append(LINE_END); 544 | strBufFile.append("Content-Disposition: form-data; name=\"" + fileName + "\"; filename=\"" + fileEntry.getKey() + "\"");// filename:参数名。fileEntry.getKey():文件名称 545 | strBufFile.append(LINE_END); 546 | strBufFile.append("Content-Type:application/octet-stream"); 547 | strBufFile.append(LINE_END); 548 | strBufFile.append(LINE_END); 549 | out.write(strBufFile.toString().getBytes("utf-8")); 550 | out.write(fileEntry.getValue());//文件 (此参数之前调用了本页面的重写方法getBytes(File f),将文件转换为字节数组了 ) 551 | out.write((LINE_END).getBytes()); 552 | } 553 | } 554 | 555 | //写入标记结束位 556 | byte[] endData = (TWO_HYPHENS + BOUNDARY + TWO_HYPHENS + LINE_END).getBytes();//写结束标记位 557 | out.write(endData); 558 | out.flush(); 559 | out.close(); 560 | 561 | /************************************输出流,写数据完成end*************************************************/ 562 | int code = connection.getResponseCode(); //获得响应码(200为成功返回) 563 | InputStream in; 564 | try { 565 | if (code == HttpURLConnection.HTTP_OK) { 566 | in = connection.getInputStream(); //获取响应流 567 | } else { 568 | in = connection.getErrorStream(); //获取响应流 569 | } 570 | } catch (SSLException e) { 571 | e.printStackTrace(); 572 | throw new IllegalArgumentException("fail to get inputStream"); 573 | } 574 | /**********读取返回的输入流信息**************/ 575 | byte[] bytes; 576 | ByteArrayOutputStream baout = new ByteArrayOutputStream(); 577 | byte[] buff = new byte[1024]; 578 | if (in != null) { 579 | int len; 580 | while ((len = in.read(buff)) != -1) { 581 | baout.write(buff, 0, len); 582 | } 583 | in.close(); 584 | } 585 | bytes = baout.toByteArray(); 586 | String ret = new String(bytes, "utf-8"); 587 | /**********封装返回的输入流信息**************/ 588 | String responseContentStr = ret; 589 | wrapper.responseCode = code; 590 | wrapper.responseContent = responseContentStr; 591 | return wrapper; 592 | } 593 | 594 | /** 595 | * 将文件转换为byte数组 596 | * 597 | * @param f file 598 | * @return byte[] bytes 599 | */ 600 | public static byte[] getBytes(File f) { 601 | try { 602 | InputStream in = new FileInputStream(f); 603 | ByteArrayOutputStream out = new ByteArrayOutputStream(1024); 604 | byte[] b = new byte[1024]; 605 | int n; 606 | while ((n = in.read(b)) != -1) 607 | out.write(b, 0, n); 608 | in.close(); 609 | out.close(); 610 | return out.toByteArray(); 611 | } catch (IOException e) { 612 | e.printStackTrace(); 613 | throw new IllegalArgumentException("File is invalid, please check again"); 614 | } 615 | } 616 | 617 | 618 | } 619 | --------------------------------------------------------------------------------