首先介绍发送短信是个什么鬼?
说白了就是一个短信服务器提供一个webservice服务供我们调用。我用到是一个提供了sendSms(String phone,String content)的方法。
下面开始唠干的,
首先我创建了一个实体类SmsConst来存放一些常量。如图所示:
实体类创建完毕之后上代码:
public class SmsTest {
public static String sendSms(String mobiles,String msg) {
if(mobiles!=null){
if(mobiles.contains(",")){
int len = mobiles.split(",").length;
if(len > 500){
return SmsConst.RSLTCODE_PHONE_FIVE_HUNDRED;
}
}else{
if(!isMobile(mobiles)){
return SmsConst.RSLTCODE_PHONE_ERROR;
}
}
}
if(msg == null || msg.equals("")){//短信为空时,不允许发送
return SmsConst.RSLTCODE_CONTENT_EMPTY;
}else{ // 短信内容为空格时,不允许发送
String nmsg = msg.replace(" ", "").replace(" ", "");
if(nmsg.length() == 0){
return SmsConst.RSLTCODE_CONTENT_BLANK;
}
}
CloseableHttpClient hc = HttpClientBuilder.create().build();
HttpPost httpPost = null;
CloseableHttpResponse response = null;
try {
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(5000).setConnectTimeout(5000)
.setSocketTimeout(5000).build();
httpPost = new HttpPost(SmsConst.SEND_SMS_URL);
httpPost.setConfig(requestConfig);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("strmobile", mobiles));
nvps.add(new BasicNameValuePair("bstrMsg", msg));
httpPost.setEntity(new UrlEncodedFormEntity(nvps,"utf-8"));
response = hc.execute(httpPost);
if (response.getStatusLine().getStatusCode() >= 400) {
Logger.log("return code is:"+response.getStatusLine().getStatusCode());
return null;
}
HttpEntity entity = response.getEntity();
if (entity != null) {
String body = EntityUtils.toString(entity);
Logger.log(httpPost.getURI()+" RES: "+body);
body=readerDOMParseXML(body);
return body;
} else {
Logger.log("response is null:");
return SmsConst.RSLTCODE_NO_DATA_ACCEPT;
}
} catch (Exception e) {
Logger.log(e.getMessage());
return SmsConst.RSLTCODE_SMS_FUNCTION_ERROR;
} finally {
try {
httpPost.abort();
response.close();
} catch (Exception e) {
httpPost=null;
response=null;
Logger.log(e.getMessage());
}
}
}
public static String readerDOMParseXML(String xml) throws Exception {
DocumentBuilderFactory buildFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = buildFactory.newDocumentBuilder();
ByteArrayInputStream bisxml = new ByteArrayInputStream(xml.getBytes());
Document document = documentBuilder.parse(bisxml);
bisxml.close();//the xml data have load in memory
Element node = document.getDocumentElement();
NodeList nodelist = node.getChildNodes();
for (int i = 0; i < nodelist.getLength(); i++)
System.out.println(nodelist.item(i).getNodeName() + "===DOM===>" + nodelist.item(i).getTextContent());
return nodelist.item(0).getTextContent();
}
/**
* 手机号验证
*
* @param str
* @return 验证通过返回true
*/
public static boolean isMobile(String str) {
Pattern p = null;
Matcher m = null;
boolean b = false;
p = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$"); // 验证手机号
m = p.matcher(str);
b = m.matches();
return b;
}
发送短信时直接调用sendSms这个方法即可,希望对你有所帮助。谢谢~