短信工具类
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.fluent.Response;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
public class SMSSender {
private static SMSSender ourInstance = new SMSSender();
public static SMSSender getInstance() {
return ourInstance;
}
private Gson gson = new Gson();
private static final String prefix = "【平台APP】";
private static final Logger logger = LogManager.getLogger(SMSSender.class);
//发送短信的地址
private static final String url = "http://IP地址:端口号/sms.aspx?action=send&userid=短信用户id&account=账号&password=密码&mobile=%s&content=%s";
public boolean sendValidation(String mobile, String content) {
if (!mobile.matches("1\\d{10}")) {
logger.error("短信发送失败!不合法的手机号:" + mobile);
return false;
}
try {
return send(mobile, URLEncoder.encode("【平台APP】" + content, "utf-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return false;
}
}
private boolean send(String mobile, String content) {
try {
Response bean = Request.Post(String.format(url, new Object[]{mobile, content})).addHeader("Accept", "text/xml").addHeader("Content-Type", "text/xml;charset=utf-8").execute();
String result = bean.returnContent().asString();
return result.contains("<returnstatus>Success</returnstatus>");
} catch (IOException e) {
e.printStackTrace();
return false;
}
class Result {
private int code;
private int fee;
private String mobile;
private String msg;
Result() {
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public int getFee() {
return fee;
}
public void setFee(int fee) {
this.fee = fee;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
class Wrapper {
private List<Result> data;
@SerializedName("total_fee")
private int total;
Wrapper() {
}
public List<Result> getData() {
return data;
}
public void setData(List<Result> data) {
this.data = data;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
}
}
}
使用方法:
SMSSender.getInstance().sendValidation("电话号码", "短信内容");