用SendCloud发送短信验证码

来源:互联网 发布:淘宝卖家提现收费吗 编辑:程序博客网 时间:2024/04/30 02:31


String smsKey = "*****";            String url = "http://xxxxx";            String vcode = createRandomVcode();//            System.out.println("验证码:" + vcode);            // 填充参数            Map<String, String> params = new HashMap<String, String>();            params.put("smsUser", "xxx");            params.put("templateId", "1");            params.put("phone", “1562566155256”);            params.put("vars", "{\"code\":\"" + vcode + "\"}");            // 对参数进行排序            Map<String, String> sortedMap = new TreeMap<String, String>(new Comparator<String>() {                @Override                public int compare(String arg0, String arg1) {                    // 忽略大小写                    return arg0.compareToIgnoreCase(arg1);                }            });            sortedMap.putAll(params);            // 计算签名            StringBuilder sb = new StringBuilder();            sb.append(smsKey).append("&");            for (String s : sortedMap.keySet()) {                sb.append(String.format("%s=%s&", s, sortedMap.get(s)));            }            sb.append(smsKey);            String sig = DigestUtils.md5Hex(sb.toString());            // 将所有参数和签名添加到post请求参数数组里            List<BasicNameValuePair> postparams = new ArrayList<>();            for (String s : sortedMap.keySet()) {                postparams.add(new BasicNameValuePair(s, sortedMap.get(s)));            }            postparams.add(new BasicNameValuePair("signature", sig));            HttpPost httpPost = new HttpPost(url);            try {                httpPost.setEntity(new UrlEncodedFormEntity(postparams, "utf8"));                DefaultHttpClient httpclient = new DefaultHttpClient();                httpclient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000);                httpclient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 100000);                HttpResponse response = httpclient.execute(httpPost);                HttpEntity entity = response.getEntity();                EntityUtils.consume(entity);//                System.out.println(EntityUtils.toString(response.getEntity()));                String str = EntityUtils.toString(response.getEntity());//                System.out.println(str);                JSONObject obj = JSONObject.fromObject(str);                boolean result = obj.getBoolean("result");            } catch (Exception e) {                viewData.error("获取验证码失败!" + e.toString());            } finally {                httpPost.releaseConnection();            }
随机生成6位数验证码:

public String createRandomVcode() {        //验证码        String vcode = "";        for (int i = 0; i < 6; i++) {            vcode = vcode + (int) (Math.random() * 9);        }        return vcode;    }



0 0
原创粉丝点击