Commit 01ec4f53 authored by 宋勇健's avatar 宋勇健

[feat]亿美软通 短信接口

parent ed242c1e
package com.hand.app.sms.controllers;
import com.alibaba.fastjson.JSONObject;
import com.hand.app.sms.service.IHclcSmsService;
import com.hand.hap.core.IRequest;
import com.hand.hap.system.controllers.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
/**
* Copyright (C) Hand Business Consulting Services
* AllRights Reserved
*
* @author: Eugene Song
* @date: 2023/6/12
* @description:
*/
@Controller
public class HclcSmsController extends BaseController {
@Autowired
private IHclcSmsService hclcSmsService;
@ResponseBody
@RequestMapping("/api/public/send/sms")
public JSONObject sendSms(HttpServletRequest request, @RequestBody(required = true) JSONObject params) {
JSONObject json = new JSONObject();
IRequest iRequest = createRequestContext(request);
json = hclcSmsService.sendSms(iRequest, params);
return json;
}
}
package com.hand.app.sms.dto;
import java.io.Serializable;
public class BaseRequest implements Serializable{
private static final long serialVersionUID = 1L;
/**
* 请求时间
*/
private long requestTime = System.currentTimeMillis();
/**
* 请求有效时间(秒)<br/>
* 服务器接受时间与请求时间对比,如果超过有效时间,拒绝此次请求<br/>
* 防止被网络抓包不断发送同一条请求<br/>
* 默认1分钟有效期
*/
private int requestValidPeriod = 60;
public long getRequestTime() {
return requestTime;
}
public void setRequestTime(long requestTime) {
this.requestTime = requestTime;
}
public int getRequestValidPeriod() {
return requestValidPeriod;
}
public void setRequestValidPeriod(int requestValidPeriod) {
this.requestValidPeriod = requestValidPeriod;
}
}
package com.hand.app.sms.dto;
import java.io.Serializable;
public class ResponseData<T> implements Serializable {
private static final long serialVersionUID = 1L;
private String code;
private T data;
public ResponseData(String code,T data){
this.code = code;
this.data = data;
}
public ResponseData(){
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
package com.hand.app.sms.dto;
public class SmsBaseRequest extends BaseRequest {
private static final long serialVersionUID = 1L;
/**
* 定时时间
* yyyy-MM-dd HH:mm:ss
*/
private String timerTime;
/**
* 扩展码
*/
private String extendedCode;
public String getTimerTime() {
return timerTime;
}
public void setTimerTime(String timerTime) {
this.timerTime = timerTime;
}
public String getExtendedCode() {
return extendedCode;
}
public void setExtendedCode(String extendedCode) {
this.extendedCode = extendedCode;
}
}
package com.hand.app.sms.dto;
import java.io.Serializable;
/**
* 单条短信发送响应
* @author Frank
*
*/
public class SmsResponse implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 系统唯一smsId
*/
private String smsId;
private String mobile;
private String customSmsId;
public SmsResponse(){
}
public SmsResponse(String smsId,String mobile,String customSmsId){
this.smsId = smsId;
this.mobile = mobile;
this.customSmsId = customSmsId;
}
public String getSmsId() {
return smsId;
}
public void setSmsId(String smsId) {
this.smsId = smsId;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getCustomSmsId() {
return customSmsId;
}
public void setCustomSmsId(String customSmsId) {
this.customSmsId = customSmsId;
}
}
package com.hand.app.sms.service;
import com.hand.app.zhongDengWang.dto.HlsWsRequests;
import com.hand.hap.core.IRequest;
import com.hand.hap.core.ProxySelf;
/**
* Copyright (C) Hand Business Consulting Services
* AllRights Reserved
*
* @author: Eugene Song
* @date: 2023/6/12
* @description:
*/
public interface IHclcSmsLogService extends ProxySelf<IHclcSmsLogService> {
HlsWsRequests createLog(IRequest iRequest, String functionName, String url, String request, Long pkValue);
HlsWsRequests updateLog(IRequest iRequest, HlsWsRequests hlsWsRequests , String statusCode,String returnStatus,String response);
}
package com.hand.app.sms.service;
import com.alibaba.fastjson.JSONObject;
import com.hand.app.esignHclc.dto.Lm005Hclc;
import com.hand.app.esignHclc.service.ILm005HclcService;
import com.hand.hap.core.IRequest;
import com.hand.hap.core.ProxySelf;
import com.hand.hap.system.service.IBaseService;
/**
* Copyright (C) Hand Business Consulting Services
* AllRights Reserved
*
* @author: Eugene Song
* @date: 2023/6/12
* @description:
*/
public interface IHclcSmsService extends ProxySelf<IHclcSmsService> {
JSONObject sendSms(IRequest iRequest, JSONObject params);
}
package com.hand.app.sms.service.impl;
import com.hand.app.sms.service.IHclcSmsLogService;
import com.hand.app.zhongDengWang.dto.HlsWsRequests;
import com.hand.app.zhongDengWang.service.IHlsWsRequestsService;
import com.hand.hap.core.IRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
/**
* Copyright (C) Hand Business Consulting Services
* AllRights Reserved
*
* @author: Eugene Song
* @date: 2023/6/12
* @description:
*/
@Service
public class HclcSmsLogServiceImpl implements IHclcSmsLogService {
@Autowired
private IHlsWsRequestsService hlsWsRequestsService;
@Override
public HlsWsRequests createLog(IRequest iRequest, String functionName, String url, String request, Long pkValue) {
HlsWsRequests hlsWsRequests = new HlsWsRequests();
hlsWsRequests.setRequestDate(new Date());
hlsWsRequests.setRequestWsdlUrl(url);
hlsWsRequests.setFunctionName(functionName);
hlsWsRequests.setStatusCode("1");
hlsWsRequests.setStatusDate(new Date());
//手机号
hlsWsRequests.setPkValue(pkValue);
hlsWsRequests.setRequestClob(request);
hlsWsRequests = hlsWsRequestsService.insertSelective(iRequest, hlsWsRequests);
return hlsWsRequests;
}
@Override
public HlsWsRequests updateLog(IRequest iRequest, HlsWsRequests hlsWsRequests, String statusCode, String returnStatus, String response) {
hlsWsRequests.setStatusCode(statusCode);
hlsWsRequests.setReturnStatus(returnStatus);
hlsWsRequests.setResponseClob(response);
hlsWsRequests = hlsWsRequestsService.updateByPrimaryKeySelective(iRequest, hlsWsRequests);
return hlsWsRequests;
}
}
package com.hand.app.sms.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.chinapay.comm.Constants;
import com.google.gson.reflect.TypeToken;
import com.hand.app.sms.dto.ResponseData;
import com.hand.app.sms.dto.SmsResponse;
import com.hand.app.sms.service.IHclcSmsLogService;
import com.hand.app.sms.service.IHclcSmsService;
import com.hand.app.sms.utils.DateUtil;
import com.hand.app.sms.utils.JsonHelper;
import com.hand.app.sms.utils.Md5;
import com.hand.app.sms.utils.http.*;
import com.hand.app.zhongDengWang.dto.HlsWsRequests;
import com.hand.hap.core.IRequest;
import com.hand.hap.intergration.dto.HapInterfaceHeader;
import com.hand.hap.intergration.service.IHapInterfaceHeaderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/**
* Copyright (C) Hand Business Consulting Services
* AllRights Reserved
*
* @author: Eugene Song
* @date: 2023/6/12
* @description:
*/
@Service
public class HclcSmsServiceImpl implements IHclcSmsService {
@Autowired
private IHapInterfaceHeaderService headerService;
@Autowired
private IHclcSmsLogService hclcSmsLogService;
//用户认证接口信息
public static final String SYS_NAME = "HCLC_SMS_API";
public static final String SEND_SMS = "sendSms";
/*事务状态*/
public static final String tranSuccess = "SUCCESS";
public static final String transFail = "FAIL";
private Logger logger = LoggerFactory.getLogger(getClass());
public String getApiUrl(String sysName, String apiName) {
//初始化接口密钥参数信息
HapInterfaceHeader headerAndLineDTO = headerService.getHeaderAndLine(sysName, apiName);
if (headerAndLineDTO == null) {
logger.info("headerAndLineDTO is null, apiName:{}, sysName:{}", apiName, sysName);
return null;
}
return headerAndLineDTO.getDomainUrl() + headerAndLineDTO.getIftUrl();
}
public boolean isNumeric(String str) {
try {
Long.parseLong(str);
return true;
} catch (NumberFormatException e) {
return false;
}
}
@Override
public JSONObject sendSms(IRequest iRequest, JSONObject params) {
logger.info("=============start setSms==================");
JSONObject result = new JSONObject();
//appId && secretKey 通过社内 传入,以后修改的时候 只需要修改 pkg 就可以 不用修改java代码重启
if (Objects.isNull(params.get("appId"))) {
result.put(Constants.RESP_CODE, transFail);
result.put("respMsg", "请求必须参数appId缺失,请检查!");
return result;
}
if (Objects.isNull(params.get("secretKey"))) {
result.put(Constants.RESP_CODE, transFail);
result.put("respMsg", "请求必须参数secretKey缺失,请检查!");
return result;
}
if (Objects.isNull(params.get("customSmsId"))) {
result.put(Constants.RESP_CODE, transFail);
result.put("respMsg", "请求必须参数customSmsId缺失,请检查!");
return result;
}
if (Objects.isNull(params.get("content"))) {
result.put(Constants.RESP_CODE, transFail);
result.put("respMsg", "请求必须参数wcontent缺失,请检查!");
return result;
}
if (Objects.isNull(params.get("mobiles"))) {
result.put(Constants.RESP_CODE, transFail);
result.put("respMsg", "请求必须参数mobiles缺失,请检查!");
return result;
}
if (!isNumeric(params.get("mobiles").toString())) {
result.put(Constants.RESP_CODE, transFail);
result.put("respMsg", "非法的电话号码!");
return result;
}
String appId = params.get("appId").toString();
// 密钥
String secretKey = params.get("secretKey").toString();
// 时间戳
String timestamp = DateUtil.toString(new Date(), "yyyyMMddHHmmss");
// 签名
String sign = Md5.md5((appId + secretKey + timestamp).getBytes());
// 接口地址(中台接口平台定义)
String sendSmsApiUrl = getApiUrl(SYS_NAME, SEND_SMS);
logger.info("token url: {}", sendSmsApiUrl);
if (sendSmsApiUrl != null) {
String request = "appId=" + appId + "&timestamp=" + timestamp + "&sign=" + sign + "&mobiles" + params.get("mobiles").toString() + "&content=" + params.get("content").toString() + "&customSmsId=" + params.get("customSmsId").toString();
HlsWsRequests log = hclcSmsLogService.createLog(iRequest, "hclc_sms", sendSmsApiUrl, request, Long.parseLong(params.get("mobiles").toString()));
setSms(iRequest, appId, sign, timestamp, sendSmsApiUrl, params.get("content").toString(), params.get("mobiles").toString(), params.get("customSmsId").toString(), null, null, log);
} else {
result.put(Constants.RESP_CODE, transFail);
result.put("respMsg", "接口平台URL未定义,请检查!");
return result;
}
return result;
}
/**
* 发送批次短信
*/
private JSONObject setSms(IRequest iRequest, String appId, String sign, String timestamp, String sendSmsApiUrl, String content, String mobiles, String customSmsId, String extendedCode, String timerTime, HlsWsRequests log) {
JSONObject result = new JSONObject();
logger.info("============= setSms==================");
Map<String, String> params = new HashMap<String, String>();
try {
params.put("appId", appId);
params.put("sign", sign);
params.put("timestamp", timestamp);
params.put("mobiles", mobiles);
params.put("content", URLEncoder.encode(content, "utf-8"));
if (customSmsId != null) {
params.put("customSmsId", customSmsId);
}
if (timerTime != null) {
params.put("timerTime", timerTime);
}
if (extendedCode != null) {
params.put("extendedCode", extendedCode);
}
} catch (UnsupportedEncodingException e) {
result.put(Constants.RESP_CODE, transFail);
result.put("respMsg", "发送失败!");
logger.error(e.getMessage());
}
HttpRequestParams<Map<String, String>> requestparams = new HttpRequestParams<Map<String, String>>();
requestparams.setCharSet("UTF-8");
requestparams.setMethod("POST");
requestparams.setParams(params);
requestparams.setUrl(sendSmsApiUrl);
HttpRequest<Map<String, String>> request;
if (sendSmsApiUrl.startsWith("https://")) {
request = new HttpsRequestKV(requestparams, null);
} else {
request = new HttpRequestKV(requestparams);
}
HttpClient client = new HttpClient();
String json = null;
try {
String mapst = "";
for (String key : params.keySet()) {
String value = params.get(key);
mapst += key + "=" + value + "&";
}
mapst = mapst.substring(0, mapst.length() - 1);
logger.info("request params: " + mapst);
HttpResponseString res = client.service(request, new HttpResponseStringPraser());
if (res == null) {
logger.error("请求接口异常");
result.put(Constants.RESP_CODE, transFail);
result.put("respMsg", "请求接口异常!");
return result;
}
if (res.getResultCode().equals(HttpResultCode.SUCCESS)) {
if (res.getHttpCode() == 200) {
json = res.getResult();
logger.info("response json: " + json);
} else {
logger.info("请求接口异常,请求码:" + res.getHttpCode());
result.put(Constants.RESP_CODE, transFail);
result.put("respMsg", "请求接口异常,请求码:" + res.getHttpCode());
return result;
}
} else {
logger.info("请求接口网络异常:" + res.getResultCode().getCode());
result.put(Constants.RESP_CODE, transFail);
result.put("respMsg", "请求接口网络异常:" + res.getResultCode().getCode());
return result;
}
} catch (Exception e) {
logger.error("解析失败");
logger.error(e.getMessage());
result.put(Constants.RESP_CODE, transFail);
result.put("respMsg", "解析失败:" + e.getMessage());
return result;
}
if (json != null) {
ResponseData<SmsResponse[]> data = JsonHelper.fromJson(new TypeToken<ResponseData<SmsResponse[]>>() {
}, json);
String code = data.getCode();
if (tranSuccess.equals(code)) {
result.put(Constants.RESP_CODE, tranSuccess);
result.put("respMsg", "发送成功!");
hclcSmsLogService.updateLog(iRequest, log, "2", "S", json);
for (SmsResponse d : data.getData()) {
logger.info("data:" + d.getMobile() + "," + d.getSmsId() + "," + d.getCustomSmsId());
}
}
}
logger.info("=============end setSms==================");
return result;
}
}
package com.hand.app.sms.utils;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateUtil {
public static final long ONE_HOUR_TIME_LONG = 3600000;
public static String toString(Date date, String format) {
String dateStr = null;
try {
SimpleDateFormat sdf = new SimpleDateFormat(format);
dateStr = sdf.format(date);
} catch (Exception e) {
}
return dateStr;
}
public static Date parseDate(String dateStr, String format) {
Date date = null;
try {
SimpleDateFormat sdf = new SimpleDateFormat(format);
date = sdf.parse(dateStr);
} catch (Exception e) {
}
return date;
}
/**
* 获取日期当天的最小时间日期,0点
*/
public static Date getMinTimeDateByDate(Date date) {
if (date == null)
return null;
String datestr = toString(date, "yyyyMMdd");
return parseDate(datestr, "yyyyMMdd");
}
/**
* 获取日期当天的最大时间日期,12点整
*/
public static Date getMaxTimeDateByDate(Date date) {
if (date == null)
return null;
String datestr = toString(date, "yyyyMMdd");
Date d = parseDate(datestr, "yyyyMMdd");
return new Date(d.getTime() + 24l * 60l * 60l * 1000l - 1l);
}
public static long subTime(Date startDate, Date endDate) {
return endDate.getTime() - startDate.getTime();
}
/**
* 获取上月第一天最早时间
* @return Date
*/
public static Date getLastMonthFirstDay() {
Calendar cal_1 = Calendar.getInstance();// 获取当前日期
cal_1.setTime(getMinTimeDateByDate(new Date()));
cal_1.add(Calendar.MONTH, -1);
cal_1.set(Calendar.DAY_OF_MONTH, 1);
return cal_1.getTime();
}
/**
* 获取上月最后一天最晚时间
* @return Date
*/
public static Date getLastMonthLastDay() {
Calendar cale = Calendar.getInstance();
cale.setTime(getMinTimeDateByDate(new Date()));
cale.add(Calendar.MONTH, -1);
cale.set(Calendar.DAY_OF_MONTH, cale.getActualMaximum(Calendar.DAY_OF_MONTH));
return new Date(cale.getTime().getTime() + 1000l * 60l * 60l * 24l - 1l);
}
/**
* 获取本月第一天最早时间
* @return Date
*/
public static Date getNowMonthFirstDay() {
Calendar cal_1 = Calendar.getInstance();// 获取当前日期
cal_1.setTime(getMinTimeDateByDate(new Date()));
cal_1.add(Calendar.MONTH, 0);
cal_1.set(Calendar.DAY_OF_MONTH, 1);
return cal_1.getTime();
}
/**
* 获取本月最后一天最晚时间
* @return Date
*/
public static Date getNowMonthLastDay() {
Calendar cale = Calendar.getInstance();
cale.setTime(getMinTimeDateByDate(new Date()));
cale.set(Calendar.DAY_OF_MONTH, cale.getActualMaximum(Calendar.DAY_OF_MONTH));
return new Date(cale.getTime().getTime() + 1000l * 60l * 60l * 24l - 1l);
}
/**
* 获取本月最后一天
* @return Date
*/
public static Date getTheMonthLastDay(Date date) {
if(date == null){
return null;
}
Calendar cale = Calendar.getInstance();
cale.setTime(date);
cale.set(Calendar.DAY_OF_MONTH, cale.getActualMaximum(Calendar.DAY_OF_MONTH));
cale.set(Calendar.HOUR, 0);
cale.set(Calendar.HOUR_OF_DAY, 0);
cale.set(Calendar.MINUTE, 0);
cale.set(Calendar.SECOND, 0);
cale.set(Calendar.MILLISECOND, 0);
return cale.getTime();
}
public static void main(String[] args) {
// System.out.println(toString(getTheMonthLastDay(new Date()), "yyyy-MM-dd HH:mm:ss"));
// System.out.println(toString(getLastMonthLastDay(), "yyyy-MM-dd HH:mm:ss"));
// System.out.println(toString(getNowMonthFirstDay(), "yyyy-MM-dd HH:mm:ss"));
// System.out.println(toString(getNowMonthLastDay(), "yyyy-MM-dd HH:mm:ss"));
}
}
package com.hand.app.sms.utils;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
/**
* json util
*
* @author 东旭
*
*/
public class JsonHelper {
private static Map<String,Gson> gsons = new HashMap<String, Gson>();
private static String DEFAULT_DATE_PATTERN = "yyyy-MM-dd HH:mm:ss";
static {
gsons.put(DEFAULT_DATE_PATTERN, createGson(DEFAULT_DATE_PATTERN));
}
private static Gson createGson(String datePattern){
return new GsonBuilder().setDateFormat(datePattern).disableHtmlEscaping().serializeNulls().create();
}
public static Gson getGson() {
return gsons.get(DEFAULT_DATE_PATTERN);
}
public static Gson getGson(String datePattern) {
Gson gson = gsons.get(datePattern);
if(gson == null){
gson = createGson(datePattern);
gsons.put(datePattern, gson);
}
return gson;
}
public static GsonBuilder newGsonBuilder() {
return new GsonBuilder();
}
/**
* 将对象转换为json串
*
* @param obj
* @return
*/
public static String toJsonString(Object obj) {
if (obj == null) {
return null;
}
return getGson().toJson(obj);
}
/**
* 将对象转换为json串,自定义日期转换规则
*
* @param obj
* @param datePattern
* @return
*/
public static String toJsonString(Object obj, String datePattern) {
if (obj == null) {
return null;
}
return getGson(datePattern).toJson(obj);
}
/**
* 将json串转换为对象
*
* @param clazz
* @param jsonString
* @return
*/
public static <T> T fromJson(Class<T> clazz, String jsonString) {
if (jsonString == null) {
return null;
}
return getGson().fromJson(jsonString, clazz);
}
/**
* 将json串转换为对象
*
* @Type type
* @param jsonString
* @return
*/
public static <T> T fromJson(TypeToken<T> token, String jsonString) {
if (jsonString == null) {
return null;
}
return getGson().fromJson(jsonString, token.getType());
}
/**
* 将json串转换为对象
*
* @Type type
* @param jsonString
* @return
*/
public static <T> T fromJson(TypeToken<T> token, String jsonString, String datePattern) {
if (jsonString == null) {
return null;
}
return getGson(datePattern).fromJson(jsonString, token.getType());
}
/**
* 将json串转换为对象
*
* @param clazz
* @param jsonString
* @return
*/
public static <T> T fromJson(Class<T> clazz, String jsonString, String datePattern) {
if (jsonString == null) {
return null;
}
return getGson(datePattern).fromJson(jsonString, clazz);
}
}
package com.hand.app.sms.utils;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* md5特征码工具
*
* @author Frank
*
*/
public class Md5 {
/**
* MD5
* @param bytes
* @return
*/
public static String md5(byte[] bytes) {
if (bytes == null || bytes.length == 0)
return null;
String s = null;
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(bytes);
byte tmp[] = md.digest();
char str[] = new char[16 * 2];
int k = 0;
for (int i = 0; i < 16; i++) {
byte byte0 = tmp[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
s = new String(str);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return s;
}
/**
* MD5[16位]
*
* @param bytes
* @return
*/
public static String md5For16(byte[] bytes) {
return md5(bytes).substring(8,24);
}
}
package com.hand.app.sms.utils;
import com.google.gson.reflect.TypeToken;
import com.hand.app.sms.dto.ResponseData;
import com.hand.app.sms.dto.SmsResponse;
import com.hand.app.sms.utils.http.*;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* Copyright (C) Hand Business Consulting Services
* AllRights Reserved
*
* @author: Eugene Song
* @date: 2023/6/12
* @description:
*/
public class Test {
/**
* 发送批次短信
*/
private static void setSms(String appId, String sign, String timestamp, String host, String content, String mobiles, String customSmsId, String extendedCode, String timerTime) {
System.out.println("============= setSms==================");
Map<String, String> params = new HashMap<String, String>();
try {
params.put("appId", appId);
params.put("sign", sign);
params.put("timestamp", timestamp);
params.put("mobiles", mobiles);
params.put("content", URLEncoder.encode(content, "utf-8"));
if (customSmsId != null) {
params.put("customSmsId", customSmsId);
}
if (timerTime != null) {
params.put("timerTime", timerTime);
}
if (extendedCode != null) {
params.put("extendedCode", extendedCode);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String json = request(params, host + "/simpleinter/sendSMS");
if (json != null) {
ResponseData<SmsResponse[]> data = JsonHelper.fromJson(new TypeToken<ResponseData<SmsResponse[]>>() {
}, json);
String code = data.getCode();
if ("SUCCESS".equals(code)) {
for (SmsResponse d : data.getData()) {
System.out.println("data:" + d.getMobile() + "," + d.getSmsId() + "," + d.getCustomSmsId());
}
}
}
System.out.println("=============end setSms==================");
}
/**
* 公共请求方法
*/
public static String request(Map<String, String> params, String url) {
HttpRequestParams<Map<String, String>> requestparams = new HttpRequestParams<Map<String, String>>();
requestparams.setCharSet("UTF-8");
requestparams.setMethod("POST");
requestparams.setParams(params);
requestparams.setUrl(url);
HttpRequest<Map<String, String>> request;
if (url.startsWith("https://")) {
request = new HttpsRequestKV(requestparams, null);
} else {
request = new HttpRequestKV(requestparams);
}
HttpClient client = new HttpClient();
String json = null;
try {
String mapst = "";
for (String key : params.keySet()) {
String value = params.get(key);
mapst += key + "=" + value + "&";
}
mapst = mapst.substring(0, mapst.length() - 1);
System.out.println("request params: " + mapst);
HttpResponseString res = client.service(request, new HttpResponseStringPraser());
if (res == null) {
System.err.println("请求接口异常");
return null;
}
if (res.getResultCode().equals(HttpResultCode.SUCCESS)) {
if (res.getHttpCode() == 200) {
json = res.getResult();
System.out.println("response json: " + json);
} else {
System.out.println("请求接口异常,请求码:" + res.getHttpCode());
}
} else {
System.out.println("请求接口网络异常:" + res.getResultCode().getCode());
}
} catch (Exception e) {
System.err.println("解析失败");
e.printStackTrace();
}
return json;
}
public static void main(String[] args) {
//账号:EUCP-EMY-SMS0-0CBEG 密码:832D74316E2SY30G
// appId
String appId = "EUCP-EMY-SMS0-0CBEG";// 请联系销售,或者在页面中 获取
// 密钥
String secretKey = "832D74316E2SY30G";// 请联系销售,或者在页面中 获取
// 接口地址
String host = "http://www.btom.cn:8080";// 请联系销售获取
// 时间戳
String timestamp = DateUtil.toString(new Date(), "yyyyMMddHHmmss");
// 签名
String sign = Md5.md5((appId + secretKey + timestamp).getBytes());
// 发送批次短信,定时时间格式yyyyMMddHHmmss
setSms(appId, sign, timestamp, host, "【某某公司】你好今天天气不错,挺风和日丽的&1=D$", "18502741388", "839273940", null, null);// 如果通道已绑定签名,可以去掉【某某公司】
}
}
This diff is collapsed.
package com.hand.app.sms.utils.http;
/**
* Http 请求实体<请求数据类型>
*
* @author Frank
*
* @param <T>
*/
public class HttpRequest<T> {
/**
* http参数
*/
private HttpRequestParams<T> httpParams;
/**
* https参数
*/
private HttpsParams httpsParams;
/**
* 内容解析器
*/
private HttpRequestPraser<T> contentPraser;
/**
* 是否https请求
*/
private boolean isHttps;
/**
*
*/
protected HttpRequest() {
}
/**
*
* @param httpParams
* http参数
* @param contentPraser
* 内容解析器
*/
protected HttpRequest(HttpRequestParams<T> httpParams, HttpRequestPraser<T> contentPraser) {
this.httpParams = httpParams;
this.contentPraser = contentPraser;
this.isHttps = false;
}
/**
*
* @param httpParams
* http参数
* @param httpsParams
* https参数
* @param contentPraser
* 内容解析器
*/
protected HttpRequest(HttpRequestParams<T> httpParams, HttpsParams httpsParams, HttpRequestPraser<T> contentPraser) {
this.httpParams = httpParams;
this.httpsParams = httpsParams;
this.contentPraser = contentPraser;
this.isHttps = true;
}
public boolean isHttps() {
return isHttps;
}
public HttpRequestParams<T> getHttpParams() {
return httpParams;
}
public void setHttpParams(HttpRequestParams<T> httpParams) {
this.httpParams = httpParams;
}
public HttpsParams getHttpsParams() {
return httpsParams;
}
public void setHttpsParams(HttpsParams httpsParams) {
this.httpsParams = httpsParams;
}
public HttpRequestPraser<T> getContentPraser() {
return contentPraser;
}
public void setContentPraser(HttpRequestPraser<T> contentPraser) {
this.contentPraser = contentPraser;
}
}
package com.hand.app.sms.utils.http;
/**
* Http 请求实体<byte[]>
*
* @author Frank
*
*/
public class HttpRequestBytes extends HttpRequest<byte[]> {
/**
*
* @param httpParams
* 请求参数
*/
public HttpRequestBytes(HttpRequestParams<byte[]> httpParams) {
super(httpParams, new HttpRequestPraserBytes());
}
}
package com.hand.app.sms.utils.http;
import java.util.Map;
/**
* Http 请求实体<Map<String, String>>
*
* @author Frank
*
*/
public class HttpRequestKV extends HttpRequest<Map<String, String>> {
/**
*
* @param httpParams
* 请求参数
*/
public HttpRequestKV(HttpRequestParams<Map<String, String>> httpParams) {
super(httpParams, new HttpRequestPraserKV());
}
}
package com.hand.app.sms.utils.http;
import java.util.Map;
/**
* Http参数
*
* @author Frank
*
* @param <T>
* 传输数据类型
*/
public class HttpRequestParams<T> {
private String url;// URL
private String charSet = "UTF-8";// 编码
private String method = "GET";// Http方法
private Map<String, String> headers;// 头信息
private String cookies;// cookie信息
private T params;// 传输数据
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getCharSet() {
return charSet;
}
public void setCharSet(String charSet) {
this.charSet = charSet;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public Map<String, String> getHeaders() {
return headers;
}
public void setHeaders(Map<String, String> headers) {
this.headers = headers;
}
public String getCookies() {
return cookies;
}
public void setCookies(String cookies) {
this.cookies = cookies;
}
public T getParams() {
return params;
}
public void setParams(T params) {
this.params = params;
}
}
package com.hand.app.sms.utils.http;
/**
* Http请求,参数解析器
*
* @author Frank
*
* @param <T>
*/
public interface HttpRequestPraser<T> {
/**
* 将请求参数转换为String<br/>
* 主要用于get方法传输
*
* @param httpParams
* 请求参数
* @return
*/
public String praseRqeuestContentToString(HttpRequestParams<T> httpParams);
/**
* 将请求参数转换为byte[]<br/>
* 主要用于post方法传输
*
* @param httpParams
* 请求参数
* @return
*/
public byte[] praseRqeuestContentToBytes(HttpRequestParams<T> httpParams);
/**
* 获取请求参数大小<br/>
* 主要用于post方法传输
*
* @param httpParams
* 请求参数
* @return
*/
public int praseRqeuestContentLength(HttpRequestParams<T> httpParams);
}
package com.hand.app.sms.utils.http;
import java.io.UnsupportedEncodingException;
/**
* Http 请求解析器:byte[]
*
* @author Frank
*
*/
public class HttpRequestPraserBytes implements HttpRequestPraser<byte[]> {
/**
* 请求内容字符串
*/
private String contentString;
@Override
public String praseRqeuestContentToString(HttpRequestParams<byte[]> httpParams) {
if (contentString != null) {
return contentString;
}
try {
contentString = new String(httpParams.getParams(), httpParams.getCharSet());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return contentString;
}
@Override
public byte[] praseRqeuestContentToBytes(HttpRequestParams<byte[]> httpParams) {
return httpParams.getParams();
}
@Override
public int praseRqeuestContentLength(HttpRequestParams<byte[]> httpParams) {
if (httpParams.getParams() != null) {
return httpParams.getParams().length;
} else {
return 0;
}
}
}
package com.hand.app.sms.utils.http;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.Map.Entry;
/**
* Http 请求解析器:Map<String, String>
*
* @author Frank
*
*/
public class HttpRequestPraserKV implements HttpRequestPraser<Map<String, String>> {
/**
* 请求内容byte数组
*/
private byte[] contentBytes;
/**
* 请求内容字符串
*/
private String contentString;
@Override
public String praseRqeuestContentToString(HttpRequestParams<Map<String, String>> httpParams) {
if (contentString != null) {
return contentString;
}
Map<String, String> params = httpParams.getParams();
if (params == null || params.size() == 0) {
return null;
}
StringBuffer buffer = new StringBuffer();
for (Entry<String, String> entry : params.entrySet()) {
if (entry.getValue() != null) {
buffer.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
}
}
String param = buffer.toString();
contentString = param.substring(0, param.length() - 1);
return contentString;
}
@Override
public byte[] praseRqeuestContentToBytes(HttpRequestParams<Map<String, String>> httpParams) {
if (contentBytes != null) {
return contentBytes;
}
String paramStr = praseRqeuestContentToString(httpParams);
if (paramStr == null) {
return null;
}
try {
contentBytes = paramStr.getBytes(httpParams.getCharSet());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return contentBytes;
}
@Override
public int praseRqeuestContentLength(HttpRequestParams<Map<String, String>> httpParams) {
praseRqeuestContentToBytes(httpParams);
if (contentBytes != null) {
return contentBytes.length;
} else {
return 0;
}
}
}
package com.hand.app.sms.utils.http;
import java.io.UnsupportedEncodingException;
/**
* Http 请求解析器:String
*
* @author Frank
*
*/
public class HttpRequestPraserString implements HttpRequestPraser<String> {
/**
* 请求内容byte数组
*/
private byte[] contentBytes;
@Override
public String praseRqeuestContentToString(HttpRequestParams<String> httpParams) {
return httpParams.getParams();
}
@Override
public byte[] praseRqeuestContentToBytes(HttpRequestParams<String> httpParams) {
if (contentBytes != null) {
return contentBytes;
}
try {
contentBytes = httpParams.getParams().getBytes(httpParams.getCharSet());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
contentBytes = null;
}
return contentBytes;
}
@Override
public int praseRqeuestContentLength(HttpRequestParams<String> httpParams) {
praseRqeuestContentToBytes(httpParams);
if (contentBytes != null) {
return contentBytes.length;
} else {
return 0;
}
}
}
package com.hand.app.sms.utils.http;
/**
* Http 请求实体<String>
*
* @author Frank
*
*/
public class HttpRequestString extends HttpRequest<String> {
/**
*
* @param httpParams
* 请求参数
*/
public HttpRequestString(HttpRequestParams<String> httpParams) {
super(httpParams, new HttpRequestPraserString());
}
}
package com.hand.app.sms.utils.http;
import java.util.List;
import java.util.Map;
/**
* Http响应
*
* @author Frank
*
*/
public class HttpResponse<T> {
/**
* Http 结果代码
*/
private HttpResultCode resultCode;
/**
* Http链接Code
*/
private int httpCode;
/**
* Http响应头
*/
private Map<String, String> headers;
/**
* http响应Cookies
*/
private List<String> cookies;
/**
* http字符集
*/
private String charSet;
/**
* http响应数据
*/
private T result;
/**
*
* @param resultCode
* Http 结果代码
* @param httpCode
* Http链接Code
* @param headers
* Http响应头
* @param cookies
* http响应Cookies
* @param charSet
* http字符集
* @param result
* http响应数据
*/
public HttpResponse(HttpResultCode resultCode, int httpCode, Map<String, String> headers, List<String> cookies, String charSet, T result) {
this.resultCode = resultCode;
this.httpCode = httpCode;
this.headers = headers;
this.cookies = cookies;
this.charSet = charSet;
this.result = result;
}
public HttpResultCode getResultCode() {
return resultCode;
}
public void setResultCode(HttpResultCode resultCode) {
this.resultCode = resultCode;
}
public int getHttpCode() {
return httpCode;
}
public void setHttpCode(int httpCode) {
this.httpCode = httpCode;
}
public Map<String, String> getHeaders() {
return headers;
}
public void setHeaders(Map<String, String> headers) {
this.headers = headers;
}
public List<String> getCookies() {
return cookies;
}
public void setCookies(List<String> cookies) {
this.cookies = cookies;
}
public String getCharSet() {
return charSet;
}
public void setCharSet(String charSet) {
this.charSet = charSet;
}
public T getResult() {
return result;
}
public void setResult(T result) {
this.result = result;
}
}
package com.hand.app.sms.utils.http;
import java.util.List;
import java.util.Map;
/**
* http 响应: byte[]
*
* @author Frank
*
*/
public class HttpResponseBytes extends HttpResponse<byte[]> {
/**
*
* @param resultCode
* Http 结果代码
* @param httpCode
* Http链接Code
* @param headers
* Http响应头
* @param cookies
* http响应Cookies
* @param charSet
* http字符集
* @param result
* http响应数据
*/
public HttpResponseBytes(HttpResultCode resultCode, int httpCode, Map<String, String> headers, List<String> cookies, String charSet, byte[] result) {
super(resultCode, httpCode, headers, cookies, charSet, result);
}
}
package com.hand.app.sms.utils.http;
import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;
/**
* 解析Byte[]响应的解析器
*
* @author Frank
*
*/
public class HttpResponseBytesPraser implements HttpResponsePraser<HttpResponseBytes> {
@Override
public HttpResponseBytes prase(HttpResultCode resultCode, int httpCode, Map<String, String> headers, List<String> cookies, String charSet, ByteArrayOutputStream outputStream) {
return new HttpResponseBytes(resultCode, httpCode, headers, cookies, charSet, outputStream == null ? null : outputStream.toByteArray());
}
}
package com.hand.app.sms.utils.http;
import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;
/**
*
* Http响应解析器
*
* @author Frank
*
* @param <T>
* http响应数据转换后实体
*/
public interface HttpResponsePraser<T> {
/**
* 解析
*
* @param resultCode
* Http 结果代码
* @param httpCode
* Http链接Code
* @param headers
* Http响应头
* @param cookies
* http响应Cookies
* @param charSet
* http字符集
* @param result
* http响应数据
*/
public T prase(HttpResultCode resultCode, int httpCode, Map<String, String> headers, List<String> cookies, String charSet, ByteArrayOutputStream outputStream);
}
package com.hand.app.sms.utils.http;
import java.util.List;
import java.util.Map;
/**
* http 响应: String
*
* @author Frank
*
*/
public class HttpResponseString extends HttpResponse<String> {
/**
*
* @param resultCode
* Http 结果代码
* @param httpCode
* Http链接Code
* @param headers
* Http响应头
* @param cookies
* http响应Cookies
* @param charSet
* http字符集
* @param result
* http响应数据
*/
public HttpResponseString(HttpResultCode resultCode, int httpCode, Map<String, String> headers, List<String> cookies, String charSet, String result) {
super(resultCode, httpCode, headers, cookies, charSet, result);
}
}
package com.hand.app.sms.utils.http;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;
/**
* 解析String响应的解析器
*
* @author Frank
*
*/
public class HttpResponseStringPraser implements HttpResponsePraser<HttpResponseString>{
@Override
public HttpResponseString prase(HttpResultCode resultCode, int httpCode, Map<String, String> headers, List<String> cookies, String charSet, ByteArrayOutputStream outputStream) {
String st = null;
try {
if(outputStream != null){
byte[] resultBytes = outputStream.toByteArray();
st = new String(resultBytes, charSet);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return new HttpResponseString(resultCode, httpCode, headers, cookies, charSet, st);
}
}
package com.hand.app.sms.utils.http;
/**
* HTTP 访问结果编码
*
* @author Frank
*
*/
public enum HttpResultCode {
SUCCESS("成功", "SUCCESS"), //
ERROR_URL_NULL("URL为空", "ERROR-URL-NULL"), //
ERROR_URL("URL访问失败", "ERROR-URL"), //
ERROR_HTTPS_SSL("HTTPS异常", "ERROR-HTTPS-SSL"), //
ERROR_METHOD("HTTP方法无法识别", "ERROR-METHOD"), //
ERROR_CHARSET("编码错误", "ERROR-CHARSET"), //
ERROR_CONNECT("访问失败", "ERROR-CONNECT"), //
ERROR_TIMEOUT("访问超时", "ERROR-TIMEOUT"), //
;
/**
* 名称
*/
private String name;
/**
* 编码
*/
private String code;
private HttpResultCode(String name, String code) {
this.name = name;
this.code = code;
}
public static String findNameByCode(String code) {
for (HttpResultCode oc : HttpResultCode.values()) {
if (oc.getCode().equals(code)) {
return oc.getName();
}
}
return null;
}
public static String findCodeByName(String name) {
for (HttpResultCode oc : HttpResultCode.values()) {
if (oc.getName().equals(name)) {
return oc.getCode();
}
}
return null;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
package com.hand.app.sms.utils.http;
/**
* https 参数
*
* @author Frank
*
*/
public class HttpsParams {
private String password;// 密钥库密钥
private String keyStorePath;// 密钥库文件地址
private String trustStorePath;// 信任库文件地址
private String algorithm;// 指定交换数字证书的加密标准:JKS
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getKeyStorePath() {
return keyStorePath;
}
public void setKeyStorePath(String keyStorePath) {
this.keyStorePath = keyStorePath;
}
public String getTrustStorePath() {
return trustStorePath;
}
public void setTrustStorePath(String trustStorePath) {
this.trustStorePath = trustStorePath;
}
public String getAlgorithm() {
return algorithm;
}
public void setAlgorithm(String algorithm) {
this.algorithm = algorithm;
}
}
package com.hand.app.sms.utils.http;
/**
* Https 请求实体<byte[]>
*
* @author Frank
*
*/
public class HttpsRequestBytes extends HttpRequest<byte[]> {
/**
*
* @param httpParams
* http请求参数
* @param httpsParams
* https参数
*/
public HttpsRequestBytes(HttpRequestParams<byte[]> httpParams, HttpsParams httpsParams) {
super(httpParams, httpsParams, new HttpRequestPraserBytes());
}
}
package com.hand.app.sms.utils.http;
import java.util.Map;
/**
* Https 请求实体<Map<String, String>>
*
* @author Frank
*
*/
public class HttpsRequestKV extends HttpRequest<Map<String, String>> {
/**
*
* @param httpParams
* http请求参数
* @param httpsParams
* https参数
*/
public HttpsRequestKV(HttpRequestParams<Map<String, String>> httpParams, HttpsParams httpsParams) {
super(httpParams, httpsParams, new HttpRequestPraserKV());
}
}
package com.hand.app.sms.utils.http;
/**
* Https 请求实体<String>
*
* @author Frank
*
*/
public class HttpsRequestString extends HttpRequest<String> {
/**
*
* @param httpParams
* http请求参数
* @param httpsParams
* https参数
*/
public HttpsRequestString(HttpRequestParams<String> httpParams, HttpsParams httpsParams) {
super(httpParams, httpsParams, new HttpRequestPraserString());
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment