java實現網易雲簡訊介面

storeWugt發表於2017-10-11

httpclient-4.3.6.jar和httpcore-4.3.3.jar jar包

首先去網易雲註冊賬號得到分配的app key 和 App Secret  開通簡訊有20條試用。使用的是httpclient post提交

請求資訊分為 請求頭和請求引數

 請求頭:必須5個引數,分別是:AppKey。Nonce。CurTime。CheckSum。Content-Type。  區分大小寫

 請求引數:mobile(手機號碼),code(驗證碼),templateid(模板id),codeLen(驗證碼長度)  非必填的。

 建立一個生成隨機驗證碼的類:

import java.security.MessageDigest;
/**
 * 驗證碼生成工具類
 * 
 *
 */
public class CheckSumBuilder {

    // 計算並獲取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'};
}

根據api提供的java程式碼建立一個測試類

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
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;


import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;




public class SendCode {
    public static void main(String[] args) throws Exception {
   
        System.out.println(sendMsg("******************"));


    }


    private static final String SERVER_URL = "https://api.netease.im/sms/sendcode.action";//傳送驗證碼的請求路徑URL
    private static final String APP_KEY = "***************************************";//網易雲信分配的賬號
    private static final String APP_SECRET = "*********";//網易雲信分配的金鑰
    private static final String NONCE = "123456";//隨機數
    //簡訊模板ID
    private static final String TEMPLATEID="3094150";
    //驗證碼長度,範圍4~10,預設為4
    private static final String CODELEN="6";
    /**
     * 
     * @param phone  手機號
     * @return
     * @throws IOException
     */
    public static String sendMsg(String phone) throws IOException {
   
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost post = new HttpPost(SERVER_URL);


        String curTime = String.valueOf((new Date().getTime() / 1000L));
        /*通過驗證碼工具類生成隨機數*/
        String checkSum = CheckSumBuilder.getCheckSum(APP_SECRET, NONCE, curTime);
        System.out.println("驗證碼:"+checkSum);
        //設定請求的header  請求頭
        post.addHeader("AppKey", APP_KEY);
        post.addHeader("Nonce", NONCE);
        post.addHeader("CurTime", curTime);
        post.addHeader("CheckSum", checkSum);
        post.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");


        //設定請求引數
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        /*啟用簡訊模板*/
        nameValuePairs.add(new BasicNameValuePair("templateid", TEMPLATEID));
        /*手機號*/
        nameValuePairs.add(new BasicNameValuePair("mobile",phone));
        /*驗證碼長度*/
        nameValuePairs.add(new BasicNameValuePair("codeLen",CODELEN));
        /*將請求頭資訊和請求引數放入一個entity裡面*/
        post.setEntity(new UrlEncodedFormEntity(nameValuePairs,"utf-8"));


        //執行請求
        HttpResponse response = httpclient.execute(post);
        /*獲取返回的資訊 是一個json字串*/
        String responseEntity = EntityUtils.toString(response.getEntity(),"utf-8");


        //判斷是否傳送成功,傳送成功返回true  獲取返回的狀態碼
        String code = JSON.parseObject(responseEntity).getString("code");
        System.out.println(code);
        if (code.equals("200")) {
            return "success";
        }
        return "error";
    }
}

然後就是一個輸入手機號碼和驗證碼的校驗類

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


import com.alibaba.fastjson.JSON;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
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;


/**
 * 校驗驗證碼輸入是否正確
 * 
 *
 */
public class MobileMessageCheck {


    public static void main(String[] args) throws Exception {
        System.out.println(checkMsg("187********","626712"));


    }


    private static final String SERVER_URL = "https://api.netease.im/sms/verifycode.action";//校驗驗證碼的請求路徑URL
    private static final String APP_KEY = "*********************************";//網易雲信分配的賬號
    private static final String APP_SECRET = "***************";//網易雲信分配的金鑰
    private static final String NONCE = "123456";//隨機數
  
    /**
     * 
     * @param phone  手機號
     * @param sum     驗證碼
     * @return
     * @throws IOException
     */
    public static String checkMsg(String phone, String sum) throws IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost post = new HttpPost(SERVER_URL);


        String curTime = String.valueOf((new Date().getTime() / 1000L));
        String checkSum = CheckSumBuilder.getCheckSum(APP_SECRET, NONCE, curTime);


        //設定請求的header
        post.addHeader("AppKey", APP_KEY);
        post.addHeader("Nonce", NONCE);
        post.addHeader("CurTime", curTime);
        post.addHeader("CheckSum", checkSum);
        post.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");


        //設定請求引數
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("mobile", phone));
        nameValuePairs.add(new BasicNameValuePair("code", sum));


        post.setEntity(new UrlEncodedFormEntity(nameValuePairs, "utf-8"));


        //執行請求
        HttpResponse response = httpclient.execute(post);
        String responseEntity = EntityUtils.toString(response.getEntity(), "utf-8");


        //判斷是否傳送成功,傳送成功返回true
        String code = JSON.parseObject(responseEntity).getString("code");
        if (code.equals("200")) {
           return "success";
        }
        return "error";
    }
}


相關文章