您的位置:首页 > 编程语言 > Java开发

模板短信接口调用java,pythoy版(一) 网易云信

2016-11-05 00:13 253 查看

说明

短信服务平台有很多,我只是个人需求,首次使用,算是测试用的,故选个网易(大公司)。

稳定性:我只测试了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接口文档南
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: