注意:这里我必须说一句,当我们调用它提供的API也好,还是我们自己使用HttpUrlConnection也好,云片的后台是有调用失败记录(错误信息),我们可以根据错误信息快速定位的。
失败记录地址:https://www.yunpian.com/dashboard/smsFailure#!/smsFailure
ok,代码基本没有东西,就一个普通的Http请求,注意,这里需要配置几个参数,我直接把我的拿出来仅供参考:
public static void main(String...args) throws IOException {
String urlString = "http://sms.yunpian.com/v2/sms/single_send.json?apikey=***************&mobile=18624915319&tpl_id=1884712&tpl_value=1234&text=【郑州深度网络科技】您的验证码是1234";
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String str = bufferedReader.readLine();
System.out.println("收到的内容" + str);
}
apikey的值我隐藏掉了,大家根据自己的对应就行了,还有一点,关于模板,首先我们自己必须要在控制点添加一个模板,必须我添加的是“【郑州深度网络科技】您的验证码是#code#”,ok,那么text的参数里就是“【郑州深度网络科技】您的验证码是1234”,后面的1234是我们自定义的。
结束了,其实很简单,可能关于模板方面会令我们很醉。
补充:上面这种请求方式在我的服务器上出现了请求参数中文乱码,换成下面的方式得到了解决:
@Override
public boolean sendSMSCode(String phone) {
String urlString = "http://sms.yunpian.com/v2/sms/single_send.json";
URL url = null;
try {
//验证码,随机四位数字
code = getCode();
url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept-Charset", "utf-8");
connection.setRequestProperty("contentType", "utf-8");
connection.setDoOutput(true);
connection.setDoInput(true);
OutputStream outputStream = connection.getOutputStream();
PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(outputStream, "utf-8"));
String con = "apikey=***************&" +
"mobile=" + phone + "&" +
"tpl_id=1884940&" +
"tpl_value=1234&text=【阿拉丁网络科技】您的验证码是"+code;
printWriter.write(con);
printWriter.flush();
InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
String str = bufferedReader.readLine();
System.out.println("云片短信:" + str);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
结束,做个记录。
笔者能力有限,不足之处欢迎之处。