1. 程式人生 > >Java使用【網易雲信】簡訊介面,給手機使用者傳送並校驗驗證碼

Java使用【網易雲信】簡訊介面,給手機使用者傳送並校驗驗證碼

package com.web;

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

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 com.alibaba.fastjson.JSON;
import com.mobile.CheckSumBuilder;

/**
 * 校驗驗證碼工具類
 * @author Administrator
 *
 */
public class MobileMessageCheck {

    private static final String SERVER_URL="https://api.netease.im/sms/verifycode.action";//校驗驗證碼的請求路徑URL
    private static final String APP_KEY="e8c86e26c09da8**************";//賬號
    private static final String APP_SECRET="0177b8******";//金鑰
    private static final String NONCE="123456";//隨機數

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