java 发送短信demo

本文介绍了一种使用Java实现短信服务的方法,包括实体类设计、发送短信的代码逻辑及异常处理等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先介绍发送短信是个什么鬼?

  说白了就是一个短信服务器提供一个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这个方法即可,希望对你有所帮助。谢谢~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值