废话不多,这次记录一下使用HttpURLConnection方式调用手机短信接口;
只为方便大家,方便自己,日后需要可直接用。
简单说一下接口要求:传递方式需要gb2312编码,代码中有所体现;
实用方法:URLEncoder.encode(userName, "GB2312") //将数据转为GB2312编码格式
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.SecureRandom;
import java.util.Random;
import java.util.concurrent.TimeUnit;
/**
* Created by wdd on 2019/03/15.
*
* @author wdd
*/
@Component
public class SendSMSUtil {
private static final String SYMBOLS = "0123456789"; // 数字
//private static final String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; 字符串
private static final Random RANDOM = new SecureRandom();
//短信平台的用户名
@Value("${sms.userName}")
private String userName;
//短信平台的密码
@Value("${sms.password}")
private String password;
//平台所提供的服务接口地址
@Value("${sms.address}")
private String address;
@Resource
private RedisTemplate redisTemplate;
public void sendSms(String mobiles) {
String code = getNonce_str(mobiles);
String Content = "【XXXXXXX服务平台】 您的验证码:" + code + " ,请在3分钟内完成操作,如非本人操作,请忽略。";
String strUrl = null;
URL url = null;
try {
strUrl = address+"username=" + URLEncoder.encode(userName, "GB2312") + "&password=" + URLEncoder.encode(password, "GB2312") + "&mobiles=" + URLEncoder.encode(mobiles, "GB2312") + "&content=" + URLEncoder.encode(Content, "GB2312");
try {
url = new URL(strUrl);
URLConnection UConn = url.openConnection();
BufferedReader breader = new BufferedReader(new InputStreamReader(UConn.getInputStream()));
String str = breader.readLine();
while (str != null) {
str = URLDecoder.decode(str, "GB2312");
String[] strs = str.split("&");
if (strs[0].replace("result=", "").trim().equals("0")) {
//发送成功后将验证码保存至redis中,时间为3分钟有效
redisTemplate.opsForValue().set("registerMobiles:sendSms"+mobiles,code,3*60, TimeUnit.SECONDS);
// str = "恭喜,短信发送成功。";
} else {
str = "短信发送失败。失败原因:" + strs[1].replace("description=", "");
}
System.out.print(str);
str = breader.readLine();
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
/**
* 生成随机数
* @return
*/
public String getNonce_str(String code) {
// 如果需要4位,那 new char[4] 即可,其他位数同理可得
char[] nonceChars = new char[6];
for (int index = 0; index < nonceChars.length; ++index) {
nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
}
return new String(nonceChars);
}
}
好了,就这么简单,有问题还请大家一定指出一起交流。
有问题留言。