首先,很多第三方短信验证码都能够,为什么我要抉择 mob 的呢?
因为 mob 的短信验证码是完全免费
并且反对 IOS,Android,Unity3d,Cocos2d- X 的集成
Mob 的官网:http://www.mob.com/
Mob 官网文档:http://www.mob.com/api/docume…
那 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-githu… 中能够看到
/**
* 获取返回数据
* @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/sm…, 申请的 URL 这个是固定的
params 包含了以下参数
params 的申请格局是 appkey=xxxx&phone=xxxx&zone=86&&code=xxxx
result 是一个 JSON 格局的字符串,如果想要提取出外面的状态码,能够应用 fastjson
JSON.parseObject(result).get(“status”).toString(),这样就取出了 String 类型的状态码
依据不同的状态码就能够判断验证是否通过
作者:意识流丶
链接:https://www.jianshu.com/p/87a…
起源:简书