java叮咚雲簡訊驗證碼介面呼叫
最近在寫後臺,所以有些方法想記錄下來,下面是叮咚雲簡訊驗證碼介面呼叫,叮咚雲的地址http://www.dingdongcloud.com/,裡面有詳細的資訊,下面是我寫的一個方法,僅供參考。
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Random;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.lang3.StringUtils;
public class SendMsgUtil {
/**
* 傳送驗證碼簡訊
*
* @param apikey
* apikey
* @param mobile
* 手機號碼(唯一,不許多個)
* @param content
* 簡訊傳送內容(必須經過utf-8格式編碼)
* @return json格式字串
*/
public static String msg(String mobile){
String URL_SEND_YZM =”https://api.dingdongcloud.com/v1/sms/sendyzm”;
String ENCODING = “UTF-8”;
String apikey = “這裡填寫從叮咚雲獲取的apikey”;
Random random = new Random();
int randomNumber = (random.nextInt(89999) + 10000);
String code = Integer.toString(randomNumber); //隨機的五位驗證碼code
//簡訊格式,可以修改
String yzmContent = “【叮咚雲】您的驗證碼是:”+code;
if (StringUtils.isNotBlank(yzmContent)) {
try {
yzmContent = URLEncoder.encode(yzmContent, ENCODING);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
NameValuePair[] data = { new NameValuePair("apikey", apikey),
new NameValuePair("mobile", mobile),
new NameValuePair("content", yzmContent) };
doPost(URL_SEND_YZM, data);
return code;
};
/**
* 基於HttpClient的post函式
*
* @param url
* 提交的URL
*
* @param data
* 提交NameValuePair引數
* @return 提交響應
*/
private static String doPost(String url, NameValuePair[] data) {
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(url);
// method.setRequestHeader("ContentType",
// "application/x-www-form-urlencoded;charset=UTF-8");
method.setRequestBody(data);
// client.getParams().setContentCharset("UTF-8");
client.getParams().setConnectionManagerTimeout(10000);
try {
client.executeMethod(method);
return method.getResponseBodyAsString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}