改方法是继 (java短信接口 ,发送短信(方式一) )文章后,新增的发送短信方法。
不同之处为:
①,使用org.apache.commons.httpclient.HttpClient 包
②,设置编码为gbk
③,可获取短信接口返回的内容,使用正则表达式,分别的result,description分别提示。
public static String smsSend(SmsBilder smsBilder) {
String errorInfo = null;
String resultInfo = null;
Throwable error = null;
try {
org.apache.commons.httpclient.HttpClient httpclient = new org.apache.commons.httpclient.HttpClient();
// 在这里执行短信发送
String url = SmsConfig.sendBasicUrl;
PostMethod post = new PostMethod(url);
post.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded;charset=gbk");
post.addParameter("SpCode", SmsConfig.spCode);
post.addParameter("LoginName", SmsConfig.loginName);
post.addParameter("Password", SmsConfig.password);
post.addParameter("MessageContent", smsBilder.getMessageContent());
post.addParameter("UserNumber", smsBilder.getUserNumber());
httpclient.executeMethod(post);
resultInfo = new String(post.getResponseBody(), "gbk");
if (resultInfo!=null) {
Pattern pattern = Pattern.compile("(?<=result\\=).*?(?=&)");
Matcher m = pattern.matcher(resultInfo);
String _result = "";
String _description = "";
while (m.find()) {
_result = m.group();
}
if (_result!=null) {
if (!_result.equals("0") && Integer.valueOf(_result)!=0) {
pattern = Pattern.compile("(?<=description\\=).*");
m = pattern.matcher(resultInfo);
while (m.find()) {
_description = m.group();
}
errorInfo = _description;
}
}
}
} catch (Exception e) {
errorInfo = "短信发送错误";
error = e;
} finally {
if (error != null) {
logger.error(errorInfo, error);
}
}
return errorInfo;
}