首先,很多第三方短信验证码都可以,为什么我要选择mob的呢?
因为mob的短信验证码是完全免费
mob的官网:http://wiki.mob.com/
MOB支持IOS,Android,Unity3d,Cocos2d-X的集成,
那Java怎么用呢?
其实MOB开发文档中有详细的介绍。
使用MOB不需要导入任何依赖,只需要把接口文档Java语言的代码拷贝下来
主要有两个方法:
1.requestData()这个是发送验证请求的方法
/**
* 发起https 请求
* @param address
* @param params
* @return
*/
public static String requestData(String address ,String params){
HttpURLConnection conn = null;
try {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager(){
public X509Certificate[] getAcceptedIssuers(){return null;}
public void checkClientTrusted(X509Certificate[] certs, String authType){}
public void checkServerTrusted(X509Certificate[] certs, String authType){}
}};
// Install the all-trusting trust manager
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new SecureRandom());
//ip host verify
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
return urlHostName.equals(session.getPeerHost());
}
};
//set ip host verify
HttpsURLConnection.setDefaultHostnameVerifier(hv);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
URL url = new URL(address);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");// POST
conn.setConnectTimeout(3000);
conn.setReadTimeout(3000);
// set params ;post params
if (params!=null) {
conn.setDoOutput(true);
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.write(params.getBytes(Charset.forName("UTF-8")));
out.flush();
out.close();
}
conn.connect();
//get result
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
String result = parsRtn(conn.getInputStream());
return result;
} else {
System.out.println(conn.getResponseCode() + " "+ conn.getResponseMessage());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
}
}
return null;
}
返回的result中有返回值和状态描述
2.parsRtn()方法,这个方法是获取返回数据
在MOB的JAVA样例程序: https://github.com/tian-github/Mob_SmsSpi中可以看到
/**
* 获取返回数据
* @param is
* @return
* @throws IOException
*/
private static String parsRtn(InputStream is) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuffer buffer = new StringBuffer();
String line = null;
boolean first = true;
while ((line = reader.readLine()) != null) {
if(first){
first = false;
}else{
buffer.append("\n");
}
buffer.append(line);
}
return buffer.toString();
}
也是直接拷过来,这两个方法我都写成静态static
了,方便调用
发送请求
String result=方法所在类.requestData(verifyUrl,params);
静态方法直接通过类.方法来调用
在官方的文档中verifyUrl
是https://webapi.sms.mob.com/sms/verify
,请求的 URL这个是固定的params
包括了以下参数
params的请求格式是
appkey=xxxx&phone=xxxx&zone=86&&code=xxxx
result
是一个JSON
格式的字符串,如果想要提取出里面的状态码,可以使用fastjson
JSON.parseObject(result).get("status").toString()
,这样就取出了String
类型的状态码
根据不同的状态码就可以判断验证是否通过