模板短信接口调用java,pythoy版(一) 网易云信
说明
短信服务平台有很多,我只是个人需求,首次使用,算是测试用的,故选个网易(大公司)。
稳定性:我只测试了15条短信... 不过前3条短信5分钟左右的延时,后面就比较快....
我只是需要发短信,等我去充值时候发现.....最少订单4w条(2000元).....就当学习吧,我也用不起啊!
安全原理:通过3个参数进行SHA1哈希计算,得到一个需要提交的参数;
而安全码(appSecret)不需要提交,这样假设数据被截获也不能被修改,否则将不能被校验。
python版
# -*- coding: utf8 -*-
'''
Created on 2016年11月03日
@author: baoluo
'''
import sys
import urllib
import urllib2
import cookielib
import hashlib
import logging
from time import time
class SendMsgTest(object):
"""网易云信 短信模板:
• 短信由三部分构成:签名+内容+变量
• 短信模板示例:尊敬的%s ,您的余额不足%s元,请及时缴费。"""
def __init__(self):
super(SendMsgTest, self).__init__()
sys.stdout.flush()
self.cookie = cookielib.CookieJar()
self.handler = urllib2.HTTPCookieProcessor(self.cookie)
self.opener = urllib2.build_opener(self.handler)
urllib2.install_opener(self.opener)
def addHeaders(self, name, value):
self.opener.addheaders.append((name, value))
def doPost(self, url, payload = None):
req = urllib2.Request(url, data = payload)
req = self.opener.open(req)
return req
def checkSum(self,appSecret,nonce,curTime):
# SHA1(AppSecret + Nonce + CurTime),三个参数拼接的字符串,
# 进行SHA1哈希计算,转化成16进制字符(String,小写)
return hashlib.sha1(appSecret + nonce + curTime).hexdigest()
def send(self):
appSecret = '368d4609c9d9'
nonce = 'baoluo' #随机数(最大长度128个字符)
curTime = str(int(time()))
self.addHeaders("AppKey", "1b9ef90f26b655da4d93293d2aa65c5e");
self.addHeaders("CheckSum", self.checkSum(appSecret,nonce,curTime));
self.addHeaders("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
self.addHeaders("CurTime", curTime);
self.addHeaders("Nonce", nonce);
templateid = '3029349' #模板ID
mobiles = "[\"15610050530\"]"
params = "[\"保罗\",\"7.7\"]"
values = {'templateid' : templateid, 'mobiles' : mobiles, 'params' : params }
postData = urllib.urlencode(values)
print postData
postUrl = 'https://api.netease.im/sms/sendtemplate.action'
try:
req = self.doPost(postUrl, postData)
if 200 == req.getcode():
res = req.read()
print res
#成功返回{"code":200,"msg":"sendid","obj":8}
#主要的返回码200、315、403、413、414、500
#详情:http://dev.netease.im/docs?doc=server&#code状态表
else:
print req.getcode()
except Exception, e:
print logging.exception(e)
if __name__ == '__main__':
sendTest = SendMsgTest()
sendTest.send()
java版
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.Date;
public class TestYunxin
{
public static void main(String[] args) throws Exception
{
System.out.println(sendMsg());
}
/**
* 发送POST方法的请求
*
* @return 所代表远程资源的响应结果
*/
public static String sendMsg()
{
String appKey = "1b9ef90f26b655da4d93293d2aa65c5e";
String appSecret = "368d4609c9d9";
String nonce = "baoluo"; // 随机数(最大长度128个字符)
String curTime = String.valueOf((new Date()).getTime() / 1000L); // 当前UTC时间戳
System.out.println("curTime: " + curTime);
String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce, curTime);
System.out.println("checkSum: " + checkSum);
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try
{
String url = "https://api.netease.im/sms/sendtemplate.action";
String encStr1 = URLEncoder.encode("保罗", "utf-8");
String encStr2 = URLEncoder.encode("name", "utf-8"); // url编码;防止不识别中文
String params = "templateid=3029349&mobiles=[\"15610050530\"]"
+ "¶ms=" + "[\"" + encStr1 + "\",\""+ encStr2 + "\"]";
System.out.println("params" + params);
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("AppKey", appKey);
conn.setRequestProperty("CheckSum", checkSum);
conn.setRequestProperty("CurTime", curTime);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
conn.setRequestProperty("Nonce", nonce);
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(params);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null)
{
result += line;
}
} catch (Exception e)
{
System.out.println("发送 POST 请求出现异常!\n" + e);
e.printStackTrace();
}
// 使用finally块来关闭输出流、输入流
finally
{
try
{
if (out != null)
{
out.close();
}
if (in != null)
{
in.close();
}
} catch (IOException ex)
{
ex.printStackTrace();
}
}
return result;
}
}
class CheckSumBuilder
{
// 计算并获取CheckSum
public static String getCheckSum(String appSecret, String nonce, String curTime)
{
return encode("sha1", appSecret + nonce + curTime);
}
// 计算并获取md5值
public static String getMD5(String requestBody)
{
return encode("md5", requestBody);
}
private static String encode(String algorithm, String value)
{
if (value == null)
{
return null;
}
try
{
MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
messageDigest.update(value.getBytes());
return getFormattedText(messageDigest.digest());
} catch (Exception e)
{
throw new RuntimeException(e);
}
}
private static String getFormattedText(byte[] bytes)
{
int len = bytes.length;
StringBuilder buf = new StringBuilder(len * 2);
for (int j = 0; j < len; j++)
{
buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
}
return buf.toString();
}
private static final char[] HEX_DIGITS =
{ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
}
参阅官网:
网易云信短信接口指南
网易云信Server Http API接口文档南
模板短信接口调用java,pythoy版(一) 网易云信的更多相关文章
- 模板短信接口调用java,pythoy版(二) 阿里大于
说明 功能:短信通知发送 + 短信发送记录查询,所有参数我没有改动,实测有效! 请自行参考 + 官方API! 短信模板示例:尊敬的${name},您的快递已在飞奔的路上,将在今天${time}送达您的 ...
- java短信接口调用
java短信接口调用 之前一直在一个传统的单位上班好多听容易的技术都没接触过,即使有时候想搞一搞类似于支付宝支付,短信接口调用,微信公众号,小程序之类等功能,一直有心无力终于跳槽了,估计是氛围的原因吧 ...
- PJzhang:exiftool图片信息提取工具和短信接口调用工具TBomb
猫宁!!! 作者:Phil Harvey 这是图片信息提取工具的地址: https://sno.phy.queensu.ca/~phil/exiftool/ 网站隶属于Sudbury 中微子天文台,从 ...
- 阿里短信接口使用(JAVA版)
近期项目需要使用短信接口,对比下选择了阿里的短信接口 以下为开发笔记: maven pom.xml中引入: <dependency> <groupId>com.aliyun&l ...
- asp.net mvc短信接口调用——阿里大于API开发心得
互联网上有许多公司提供短信接口服务,诸如网易云信.阿里大于等等.我在自己项目里需要使用到短信服务起到通知作用,实际开发周期三天,完成配置.开发和使用,总的说,阿里大于提供的接口易于开发,非常的方便,短 ...
- 短信接口调用以及ajax发送短信接口实现以及前端样式
我们短信api用的是云信使平台提供的非免费短信服务:官网提供的demo有两种,分别是function加其调用.class文件加其调用. 在这里我们用class文件加调用: 首先,ThinkPHP里面自 ...
- zabbix短信接口调用
#!/bin/bash TIME=`date +%Y-%m-%d` KEY="UJK9rk50HD8du8JE8h87RUor0KERo5jk" username="za ...
- 中国网建SMS短信接口调用(java发送和接收手机短信)
1.先注册账号,一定要填写好签名格式.不填会返回-51错误. 代码信息接口详细==>http://sms.webchinese.cn/api.shtml . 2.测试代码 package ...
- Aliyun发送短信接口调用方法
aliyun新版发送短信讲的不是很清晰,初次使用一堆dll不知道用哪个,以.net为例 申请SignName与Template_code请先申请,一般两个小时能通过 一.https://help.al ...
随机推荐
- Karma 5:集成 Karma 和 Angular2
集成 Karma 和 Angular2 我们需要做很多工作,由于需要使用 TypeScript 进行开发,首先需要正确配置 Typescript ,然后正确配置对 Angular2 的引用.还要创建 ...
- Extract QQ from iPhone and analyze it
QQ is one of the most popular chat App in the world. Now let me show you how to extract QQ from iPho ...
- 1.No MBR错误
如果提示如下错误: Error: No MBR is found at SD/MMC. Hint: use f ...
- Unable to open file 'TYPES.OBJ'
Unable to open file 'TYPES.OBJ' 有旧的控件HPP文件存在,旧控件的HPP文件里是Types::TPoint: 新的Berlin的是System::Types::TPoi ...
- android 根据包名打开app程序
如: 如打开微信: 查看包名的工具app:http://pan.baidu.com/s/1kVK2ER9 效果如下: 查看包名.版本和签名的工具app:http://pan.baidu.com/s/1 ...
- 跨域文件 clientaccesspolicy.xml
<?xml version="1.0" encoding="utf-8" ?> <access-policy> <cross-do ...
- Hibernate对象的状态
站在持久化的角度, Hibernate 把对象分为 4 种状态: 1. 持久化状态 2. 临时状态 3. 游离状态 4. 删除状态 Session 的特定方法能使对象从一个状态转换到另一个状态. 下面 ...
- 第三方控件radupload 使用方式以及报错处理
使用方式: 1.web.config 中需要加入: <httpHandlers> <add verb="*" path="Telerik.Rad ...
- java时间相减(转载)
package com.jie.java.phone; import java.text.ParseException; import java.text.SimpleDateFormat; impo ...
- 根据excel表格中的内容更新Sql数据库
关于[无法创建链接服务器 "(null)" 的 OLE DB 访问接口 SQL Server 2008读取EXCEL数据时,可能会报这个错误:无法创建链接服务器 "(nu ...