当前位置: 首页 > Web前端 > HTML

使用Mob发送短信验证码

时间:2023-03-27 23:37:49 HTML

首先,第三方短信验证码很多,为什么要选择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请求*@paramaddress*@paramparams*@return*/publicstaticStringrequestData(Stringaddress,Stringparams){HttpURLConnectionconn=null;try{//创建一个不验证证书链的信任管理器TrustManager[]trustAllCerts=newTrustManager[]{newX509TrustManager(){publicX509Certificate[]getAcceptedIssuers(){returnnull;}publicvoidcheckClientTrusted(X509Certificate[]certs,StringauthType){}publicvoidcheckServerTrusted(X509Certificate[]certs,StringauthType){}}};//安装完全信任的信任管理器SSLContextsc=SSLContext.getInstance("TLS");sc.init(空,trustAllCerts,newSecureRandom());//ip主机验证HostnameVerifierhv=newHostnameVerifier(){publicbooleanverify(StringurlHostName,SSLSessionsession){returnurlHostName.equals(session.getPeerHost());}};//设置ip主机验证HttpsURLConnection.setDefaultHostnameVerifier(hv);HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());网址url=新网址(地址);conn=(HttpURLConnection)url.openConnection();conn.setRequestMethod("POST");//POSTconn.setConnectTimeout(3000);conn.setReadTimeout(3000);//设置参数;发布参数if(params!=null){conn.setDoOutput(true);DataOutputStreamout=newDataOutputStream(conn.getOutputStream());out.write(params.getBytes(Charset.forName("UTF-8")));out.flush();关闭();}conn.connect();//获取结果if(conn.getResponseCode()==HttpURLConnection.HTTP_OK){Stringresult=parsRtn(conn.getInputStream());返回结果;}else{System.out.println(conn.getResponseCode()+""+conn.getResponseMessage());}}catch(Exceptione){e.printStackTrace();}finally{if(conn!=null){conn.disconnect();}}returnnull;}返回结果有返回值和状态描述2.parsRtn()方法,该方法是获取返回数据,可以在MOB的JAVA示例程序中看到:https://github。com/tian-github...To/***获取返回数据*@paramis*@return*@throwsIOException*/privatestaticStringparsRtn(InputStreamis)throwsIOException{BufferedReaderreader=newBufferedReader(newInputStreamReader(is));StringBufferbuffer=newStringBuffer();字符串行=空;布尔值优先=true;while((line=reader.readLine())!=null){if(first){first=false;}else{buffer.append("\n");}buffer.append(line);}returnbuffer.toString();}也是直接复制过来的。这两个方法我都写成静态的了,方便调用和发送请求Stringresult=方法所在的类。请求数据(verifyUrl,参数);通过类直接调用静态方法。Method官方文档中verifyUrl为https://webapi.sms.mob.com/sm...,请求的URLThisisfixedparams包含以下参数。params的请求格式为appkey=xxxx&phone=xxxx&zone=86&&code=xxxxresult为JSON格式的字符串。如果想提取里面的状态码,可以使用fastjsonJSON.parseObject(result)。get("status").toString(),这样就取出了String类型的状态码。根据不同的状态码,可以判断是否通过验证作者:意识流链接:https://www.jianshu.com/p/87a...来源:简书