网易云信短信验证

// 计算并获取CheckSum
   public static String getCheckSum(String appSecret, String nonce, String curTime) {
       return encode("sha1", appSecret + nonce + curTime);
   }


   // 计算并获取md5值
   public static String getMD5(String requestBody) {
       return encode("md5", requestBody);
   }


   private static String encode(String algorithm, String value) {
       if (value == null) {
           return null;
       }
       try {
           MessageDigest messageDigest
                   = MessageDigest.getInstance(algorithm);
           messageDigest.update(value.getBytes());
           return getFormattedText(messageDigest.digest());
       } catch (Exception e) {
           throw new RuntimeException(e);
       }
   }
   private static String getFormattedText(byte[] bytes) {
       int len = bytes.length;
       StringBuilder buf = new StringBuilder(len * 2);
       for (int j = 0; j < len; j++) {
           buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
           buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
       }
       return buf.toString();
   }
   private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5',
           '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
   public static void main(String[] args) throws Exception{
       DefaultHttpClient httpClient = new DefaultHttpClient();
      // String url = "https://api.netease.im/nimserver/user/create.action";
       String url = "https://api.netease.im/sms/sendcode.action"; // 获取验证码的固定请求路径
       HttpPost httpPost = new HttpPost(url);
       String appKey = "8cc10c0e51609a063105435ae17c91c91"; //填写你自己的appkey
       String appSecret = "5ed5e849b68e";
       String nonce =  "12345";
       String curTime = String.valueOf((new Date()).getTime() / 1000L);
       String checkSum = getCheckSum(appSecret, nonce ,curTime);//参考 计算CheckSum的java代码
       // 设置请求的header
       httpPost.addHeader("AppKey", appKey);
       httpPost.addHeader("Nonce", nonce);
       httpPost.addHeader("CurTime", curTime);
       httpPost.addHeader("CheckSum", checkSum);
       httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
       String mobile = "13986500600";
       String code = "1396";
       String templateid = "1396";
       JSONArray array =new JSONArray();
       array.add("name");
       String params = array.toJSONString();
       // 设置请求的参数
       List nvps = new ArrayList();
       nvps.add(new BasicNameValuePair("mobile", mobile));        
       nvps.add(new BasicNameValuePair("code", code));
       nvps.add(new BasicNameValuePair("templateid", templateid));
       nvps.add(new BasicNameValuePair("params", params));
       httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
       // 执行请求
       HttpResponse response = httpClient.execute(httpPost);
       // 打印执行结果
       System.out.println(EntityUtils.toString(response.getEntity(), "utf-8"));
   }

你可能感兴趣的:(网易云信短信验证)