码迷,mamicode.com
首页 > 移动开发 > 详细

使用java程序发送手机短信

时间:2021-06-03 18:10:10      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:asi   hostname   maven   catch   script   exception   check   eve   ted   

一:进入网建短信通 http://sms.webchinese.cn/reg.shtml

注册用户,登录用户,找到修改短信秘钥,修改签名

技术图片

 

 二:使用idea创建一个maven项目导入以下依赖:

  <dependency>
            <groupId>org.ops4j.pax.url</groupId>
            <artifactId>pax-url-aether</artifactId>
            <version>2.6.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.13</version>
        </dependency>

三:编写工具类

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);
    }


    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);
    }


    @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
     * @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
     * @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;
        }
    }
}

 

:创建测试类:

class test {
     //用户名
    private static String Uid = "";
    //短信秘钥
    private static String Key = "";
    //电话号码
    private static String smsMob = "";
    //短信内容
    private static String smsText = "";
    public static void main(String[] args) {
        HttpClientUtil client = HttpClientUtil.getInstance();
   while (true){
      int result = client.sendMsgUtf8(Uid, Key, smsText, smsMob);
        if(result>0){
            System.out.println("成功发送"+result+"条信息");
        }else{
            System.out.println(client.getErrorMsg(result));
        }
    }
}
}

 

使用java程序发送手机短信

标签:asi   hostname   maven   catch   script   exception   check   eve   ted   

原文地址:https://www.cnblogs.com/xioayuan/p/14844708.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!