需求分析
存有电话号码的excel表格,利用java读取,采用SMS发短信息
步骤
1、数据预处理,将excel中电话号码转化为文本类型,避免导致数据读写时出现问题
2、注册SMS,得到Uid、Key
3、具体代码
代码
1、新建工具类HttpClientUtil
package com.cqu.utils;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.util.PublicSuffixMatcher;
import org.apache.http.conn.util.PublicSuffixMatcherLoader;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
/** * @author:luotiantian * @date 2020/9/29 18:28 */
public class HttpClientUtil {
private RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(15000)
.setConnectTimeout(15000)
.setConnectionRequestTimeout(15000)
.build();
private static HttpClientUtil instance = null;
private HttpClientUtil(){
}
public static HttpClientUtil getInstance(){
if (instance == null) {
instance = new HttpClientUtil();
}
return instance;
}
/** * 发送 post请求 * @param httpUrl 地址 */
public String sendHttpPost(String httpUrl) {
HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
return sendHttpPost(httpPost,"utf-8");
}
/** * 发送 post请求 * @param httpUrl 地址 * @param maps 参数 * @param type 字符编码格式 */
public String sendHttpPost(String httpUrl, Map<String, String> maps, String type) {
HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
// 创建参数队列
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
for (String key : maps.keySet()) {
nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));
}
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, type));
} catch (Exception e) {
e.printStackTrace();
}
return sendHttpPost(httpPost,type);
}
/** * 发送Post请求 * @param httpPost * @return */
private String sendHttpPost(HttpPost httpPost,String reponseType) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
HttpEntity entity = null;
String responseContent = null;
try {
// 创建默认的httpClient实例.
httpClient = HttpClients.createDefault();
httpPost.setConfig(requestConfig);
// 执行请求
response = httpClient.execute(httpPost);
entity = response.getEntity();
responseContent = EntityUtils.toString(entity, reponseType);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 关闭连接,释放资源
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return responseContent;
}
/** * 发送 get请求 * @param httpUrl */
public String sendHttpGet(String httpUrl) {
HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求
return sendHttpGet(httpGet);
}
/** * 发送 get请求Https * @param httpUrl */
public String sendHttpsGet(String httpUrl) {
HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求
return sendHttpsGet(httpGet);
}
/** * @Title: sendMsgUtf8 * @Description: TODO(发送utf8) * @param: @param Uid * @param: @param Key * @param: @param content * @param: @param mobiles * @param: @return * @date: 2017-3-22 下午5:58:07 * @throws */
@SuppressWarnings({
"rawtypes", "unchecked" })
public int sendMsgUtf8(String Uid,String Key,String content,String mobiles){
Map maps = new HashMap();
maps.put("Uid", Uid);
maps.put("Key", Key);
maps.put("smsMob", mobiles);
maps.put("smsText", content);
String result = sendHttpPost("http://utf8.sms.webchinese.cn", maps, "utf-8");
return Integer.parseInt(result);
}
/** * @Title: sendMsgUtf8 * @Description: TODO(发送utf8) * @param: @param Uid * @param: @param Key * @param: @param content * @param: @param mobiles * @param: @return * @return: int * @author: ly * @date: 2017-3-22 下午5:58:07 * @throws */
@SuppressWarnings({
"rawtypes", "unchecked" })
public int sendMsgGbk(String Uid,String Key,String content,String mobiles){
Map maps = new HashMap();
maps.put("Uid", Uid);
maps.put("Key", Key);
maps.put("smsMob", mobiles);
maps.put("smsText", content);
String result = sendHttpPost("http://gbk.sms.webchinese.cn", maps, "gbk");
return Integer.parseInt(result);
}
/** * 发送Get请求 * @param httpPost * @return */
private String sendHttpGet(HttpGet httpGet) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
HttpEntity entity = null;
String responseContent = null;
try {
// 创建默认的httpClient实例.
httpClient = HttpClients.createDefault();
httpGet.setConfig(requestConfig);
// 执行请求
response = httpClient.execute(httpGet);
entity = response.getEntity();
responseContent = EntityUtils.toString(entity, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 关闭连接,释放资源
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return responseContent;
}
/** * 发送Get请求Https * @param httpPost * @return */
private String sendHttpsGet(HttpGet httpGet) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
HttpEntity entity = null;
String responseContent = null;
try {
// 创建默认的httpClient实例.
PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader.load(new URL(httpGet.getURI().toString()));
DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher);
httpClient = HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier).build();
httpGet.setConfig(requestConfig);
// 执行请求
response = httpClient.execute(httpGet);
entity = response.getEntity();
responseContent = EntityUtils.toString(entity, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 关闭连接,释放资源
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return responseContent;
}
/** * @Title: getErrorMsg * @Description: TODO(返回异常原因) * @param: @param errorCode */
public String getErrorMsg(int errorCode){
if(errorCode==-1){
return "没有该用户账户";
}else if(errorCode==-2){
return "接口密钥不正确";
}else if(errorCode==-3){
return "短信数量不足";
}else if(errorCode==-4){
return "手机号格式不正确";
}else if(errorCode==-21){
return "MD5接口密钥加密不正确";
}else if(errorCode==-11){
return "该用户被禁用";
}else if(errorCode==-14){
return "短信内容出现非法字符";
}else if(errorCode==-41){
return "手机号码为空";
}else if(errorCode==-42){
return "短信内容为空";
}else if(errorCode==-51){
return "短信签名格式不正确";
}else if(errorCode==-6){
return "IP限制";
}else{
return "未知错误码:"+errorCode;
}
}
}
2、具体实现方法
package com.cqu.test;
import com.cqu.utils.HttpClientUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.*;
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
/** * @author:luotiantian * @date 2020/9/29 18:31 */
// 网通SMS :http://sms.webchinese.com.cn/user/?action=pay
public class NewTest {
private static String Uid = "xx";//自己去sms注册
private static String Key = "xx";
private static String smsMob = "电话号码";
private static String smsText;//短信文本
public int sms(String[] arr) throws IOException {
//txt文件存入短信通知类容
//注意发送短信时,末尾一定要加正规签名发送,签名格式【中文公司名称】或【中文网站名称】否则发送不成。
InputStream fis = new FileInputStream("D:\\sms.txt");//用.txt文件存放短信文本
byte[] b = new byte[1024];
int len;
len = fis.read(b);
String s = new String(b, 0, len);
System.out.println(s);
fis.close();
smsText = s + "【XXXX】";//正规签名
HttpClientUtil instance = HttpClientUtil.getInstance();
//单条测试
/* int result = instance.sendMsgUtf8(Uid, Key, smsText, smsMob); if (result > 0) { System.out.println("成功条数=" + result); } else { System.out.println(instance.getErrorMsg(result)); } return result;*/
int counts=arr.length;
int result;
int allnum=0;
for(int i=0;i<counts;i++){
smsMob=arr[i];
result = instance.sendMsgUtf8(Uid, Key, smsText, smsMob);
allnum+=result;
if (result > 0) {
// System.out.println("成功条数=" + result);
} else {
System.out.println(instance.getErrorMsg(result));
}
}
return allnum;
}
public static void main(String[] args) throws Exception {
NewTest NT=new NewTest();
String[] excel = NT.excel();
int sms = NT.sms(excel);
System.out.println(sms);
}
//处理表格数据
public String[] excel() throws Exception {
File file=new File("C:xx.xlsx");//包含电话号码信息的表格
//用流的方式先读取到你想要的excel的文件
InputStream inp = new FileInputStream(file);
XSSFWorkbook workbook = new XSSFWorkbook(inp);
//得到第一个sheet
XSSFSheet sheet = workbook.getSheetAt(0);
//行数
Integer lastRowNum = sheet.getLastRowNum();
//存电话号码的String数组
String[] res=new String[lastRowNum];
for(int i=0;i<lastRowNum;i++){
//得到第i行
XSSFRow row1= sheet.getRow(i+1);
//第7列是电话号码
/* 先将电话号码所在excel列转化为文本类型 * */
XSSFCell cell =row1.getCell(7);
res[i]= cell.toString();
}
//打印
for(String s:res){
System.out.println(s);
}
inp.close();
return res;
}
}