发送短信工具类SMSClient.java
package com.dhxx.common.mas;
import com.dhxx.common.util.JSONUtils;
import com.dhxx.common.util.Md5Util;
import org.apache.commons.codec.binary.Base64;
import java.io.*;
import java.net.*;
public class SMSClient {
private static String apId="xxxxxx";
private static String secretKey="xxxxxx";
private static String ecName = "xxxxxx";//集团名称
private static String sign = "70Ldxxxxx";//网关签名编码
private static String addSerial = "";//拓展码 填空
public static String msg = "这是发送短信的内容!";
public static String url = "http://112.35.1.155:1992/sms/norsubmit";//请求url
public static int sendMsg(String mobiles,String content){
SendReq sendReq = new SendReq();
sendReq.setApId(apId);
sendReq.setEcName(ecName);
sendReq.setSecretKey(secretKey);
sendReq.setContent(content);
sendReq.setMobiles(mobiles);
sendReq.setAddSerial(addSerial);
sendReq.setSign(sign);
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(sendReq.getEcName());
stringBuffer.append(sendReq.getApId());
stringBuffer.append(sendReq.getSecretKey());
stringBuffer.append(sendReq.getMobiles());
stringBuffer.append(sendReq.getContent());
stringBuffer.append(sendReq.getSign());
stringBuffer.append(sendReq.getAddSerial());
//System.out.println(stringBuffer.toString());
sendReq.setMac(Md5Util.MD5(stringBuffer.toString()).toLowerCase());
//System.out.println(sendReq.getMac());
String reqText = JSONUtils.obj2json(sendReq);
String encode = Base64.encodeBase64String(reqText.getBytes());
//System.out.println(encode);
String resStr = sendPost(url,encode);
System.out.print("发送短信结果:"+resStr);
SendRes sendRes = JSONUtils.json2pojo(resStr,SendRes.class);
if(sendRes.isSuccess() && !"".equals(sendRes.getMsgGroup()) && "success".equals(sendRes.getRspcod())){
return 1;
}else{
return 0;
}
}
/**
* main方法测试发送短信,返回1表示成功,0表示失败
*/
public static void main(String[] args){
int result = sendMsg("xxxxxx",msg);
System.out.println(result);
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数
* @return 所代表远程资源的响应结果
*/
private static String sendPost(String url, String param) {
OutputStreamWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("contentType","utf-8");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
conn.setDoOutput(true);
conn.setDoInput(true);
out = new OutputStreamWriter(conn.getOutputStream());
out.write(param);
out.flush();
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += "\n" + line;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
}
这里需要注意的是apId和secretKey一般不会搞错,但是集团名称ecName一定要写对,否则就会提示{“msgGroup”:”“,”rspcod”:”InvalidUsrOrPwd”,”success”:false},无效的用户名和密码,还有一个就是mac字段sendReq.setMac(Md5Util.MD5(stringBuffer.toString()).toLowerCase());
MD5加密过后一定要把它变成小写.toLowerCase(),否则也会出错。
发送短信实体SendReq.java
package com.dhxx.common.mas;
/**
* 发送短信请求实体
*/
public class SendReq {
private String ecName;//集团客户名称
private String apId;//用户名
private String secretKey;//密码
private String mobiles;//手机号码逗号分隔。(如“18137282928,18137282922,18137282923”)
private String content;//发送短信内容
private String sign;//网关签名编码,必填,签名编码在中国移动集团开通帐号后分配,可以在云MAS网页端管理子系统-SMS接口管理功能中下载。
private String addSerial;//扩展码,根据向移动公司申请的通道填写,如果申请的精确匹配通道,则填写空字符串(""),否则添加移动公司允许的扩展码。
private String mac;//API输入参数签名结果,签名算法:将ecName,apId,secretKey,mobiles,content ,sign,addSerial按照顺序拼接,然后通过md5(32位小写)计算后得出的值。
public String getEcName() {
return ecName;
}
public void setEcName(String ecName) {
this.ecName = ecName;
}
public String getApId() {
return apId;
}
public void setApId(String apId) {
this.apId = apId;
}
public String getSecretKey() {
return secretKey;
}
public void setSecretKey(String secretKey) {
this.secretKey = secretKey;
}
public String getMobiles() {
return mobiles;
}
public void setMobiles(String mobiles) {
this.mobiles = mobiles;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getSign() {
return sign;
}
public void setSign(String sign) {
this.sign = sign;
}
public String getAddSerial() {
return addSerial;
}
public void setAddSerial(String addSerial) {
this.addSerial = addSerial;
}
public String getMac() {
return mac;
}
public void setMac(String mac) {
this.mac = mac;
}
}
响应发送结果实体SendRes.java
package com.dhxx.common.mas;
/**
* 发送短信响应实体
*/
public class SendRes {
private String rspcod;//响应码
private String msgGroup;//消息批次号,由云MAS平台生成,用于验证短信提交报告和状态报告的一致性(取值msgGroup)注:如果数据验证不通过msgGroup为空
private boolean success;
public String getRspcod() {
return rspcod;
}
public void setRspcod(String rspcod) {
this.rspcod = rspcod;
}
public String getMsgGroup() {
return msgGroup;
}
public void setMsgGroup(String msgGroup) {
this.msgGroup = msgGroup;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
}
鉴于有朋友要求看json类和MD5工具类,这里也贴出来
MD5工具类Md5Util.java:
import java.security.MessageDigest;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
/**
* MD5加密/验证工具类
*
* @author bluesky
*
*/
public class Md5Util {
static final char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
/**
* 生成MD5码
*
* @param plainText
* 要加密的字符串
* @return md5值
*/
public final static String MD5(String plainText) {
try {
byte[] strTemp = plainText.getBytes("UTF-8");
MessageDigest mdTemp = MessageDigest.getInstance("MD5");
mdTemp.update(strTemp);
byte[] md = mdTemp.digest();
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
return null;
}
}
/**
* 生成MD5码
*
* @param plainText
* 要加密的字符串
* @return md5值
*/
public final static String MD5(byte[] plainText) {
try {
byte[] strTemp = plainText;
MessageDigest mdTemp = MessageDigest.getInstance("MD5");
mdTemp.update(strTemp);
byte[] md = mdTemp.digest();
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
return null;
}
}
/**
* 先进行HmacSHA1转码再进行Base64编码
* @param data 要SHA1的串
* @param key 秘钥
* @return
* @throws Exception
*/
public static String HmacSHA1ToBase64(String data, String key) throws Exception {
SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(signingKey);
byte[] rawHmac = mac.doFinal(data.getBytes());
return Base64.encodeBase64String(rawHmac);
}
/**
* 校验MD5码
*
* @param text
* 要校验的字符串
* @param md5
* md5值
* @return 校验结果
*/
public static boolean valid(String text, String md5) {
return md5.equals(MD5(text)) || md5.equals(MD5(text).toUpperCase());
}
/**
*
* @param params
* @return
*/
public static String MD5(String... params) {
StringBuilder sb = new StringBuilder();
for (String param : params) {
sb.append(param);
}
return MD5(sb.toString());
}
}
json工具类JSONUtils.java:
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* @author jhy
* @description json工具
*/
public class JSONUtils {
private final static ObjectMapper objectMapper = new ObjectMapper();
private static Logger log = LoggerFactory.getLogger(JSONUtils.class);
private JSONUtils() {
}
public static ObjectMapper getInstance() {
return objectMapper;
}
/**
* javaBean,list,array convert to json string
*/
public static String obj2json(Object obj) {
try {
return objectMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
log.error(e.getMessage());
}
return null;
}
/**
* javaBean,list,array convert to json string
*/
public static String obj2jsonInoreString(Object obj) {
try {
return objectMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
log.error(e.getMessage());
}
return null;
}
/**
* json string convert to javaBean
*/
public static T json2pojo(String jsonStr, Class clazz) {
try {
return objectMapper.readValue(jsonStr, clazz);
} catch (JsonParseException e) {
// TODO Auto-generated catch block
log.error(e.getMessage());
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
log.error(e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
log.error(e.getMessage());
}
return null;
}
/**
* json string convert to map
*/
public static Map json2map(String jsonStr) {
try {
return objectMapper.readValue(jsonStr, Map.class);
} catch (JsonParseException e) {
// TODO Auto-generated catch block
log.error(e.getMessage());
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
log.error(e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
log.error(e.getMessage());
}
return null;
}
/**
* json string convert to map with javaBean
*/
public static Map json2map(String jsonStr, Class clazz){
Map> map = null;
try {
map = objectMapper.readValue(jsonStr,
new TypeReference