PHP 代码实例
<?php
/**
- Created by Zhongxinrongda.
- Date: 2017/3/3
- Time: 14:34
- 功能:云信通企业信使短信接口类
- 说明:
一下代码只是提供简单的功能,方便客户的测试,如有其他需求,客户可根据实际自行更改代码。
/
class smsApi{
/*- @param string $sms_send_url 短信发送接口url
- @param string $sms_query_url 短信余额查询接口url
- @param string $userid 企业id
- @param string $account 短信账户
- @param string $password 账户密码
*/
var $sms_send_url=‘‘;
var $sms_query_url=‘‘;
var $userid=‘‘;
var $account=‘‘;
var $password=‘‘;
public function sendSms($mobile,$content,$sendTime=‘‘){
$post_data=array(
‘userid‘=>$this->userid,
‘account‘=>$this->account,
‘password‘=>$this->password,
‘mobile‘=>$mobile,
‘content‘=>$content,
‘sendTime‘=>$sendTime //发送时间,为空是即时发送
);
$url=$this->sms_send_url;
$o=‘‘;
foreach ($post_data as $k=>$v)
{
$o.="$k=".urlencode($v).‘&‘;
}
$post_data=substr($o,0,-1);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
//curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //如果需要将结果直接返回到变量里,那加上这句。
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
}
Java 代码实例
package com.zxrd.interfacej;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
/**
- 云信通企业信使短信接口Java示例
- @param url 应用地址,类似于http://ip:port/sms.aspx
- @param userid 用户ID
- @param account 账号
- @param pssword 密码
- @param mobile 手机号码,多个号码使用","分割
- @param content 短信内容
- @return 返回值定义参见HTTP协议文档
- @throws Exception
*/
public class Sms {
public static String HTTPPost(String sendUrl, String sendParam) {
String codingType = "UTF-8";
StringBuffer receive = new StringBuffer();
BufferedWriter wr = null;
try {
//建立连接
URL url = new URL(sendUrl);
HttpURLConnection URLConn = (HttpURLConnection) url.openConnection();
URLConn.setDoOutput(true);
URLConn.setDoInput(true);
((HttpURLConnection) URLConn).setRequestMethod("POST");
URLConn.setUseCaches(false);
URLConn.setAllowUserInteraction(true);
HttpURLConnection.setFollowRedirects(true);
URLConn.setInstanceFollowRedirects(true);
URLConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
URLConn.connect();
DataOutputStream dos = new DataOutputStream(URLConn.getOutputStream());
dos.writeBytes(sendParam);
BufferedReader rd = new BufferedReader(new InputStreamReader(
URLConn.getInputStream(), codingType));
String line;
while ((line = rd.readLine()) != null) {
receive.append(line).append("\r\n");
}
rd.close();
} catch (java.io.IOException e) {
receive.append("访问产生了异常-->").append(e.getMessage());
e.printStackTrace();
} finally {
if (wr != null) {
try {
wr.close();
} catch (IOException ex) {
ex.printStackTrace();
}
wr = null;
}
}
return receive.toString();
}
//发送短信
public static String send(String sendUrl, String userid, String account,
String password, String mobile, String content) {
String codingType = "UTF-8";
StringBuffer sendParam = new StringBuffer();
try {
sendParam.append("action=").append("send");
sendParam.append("&userid=").append(userid);
sendParam.append("&account=").append(URLEncoder.encode(account, codingType));
sendParam.append("&password=").append(URLEncoder.encode(password, codingType));
sendParam.append("&mobile=").append(mobile);
sendParam.append("&content=").append(URLEncoder.encode(content, codingType));
} catch (Exception e) {
//处理异常
e.printStackTrace();
}
return Sms.HTTPPost(sendUrl,sendParam.toString());
}
//查询余额
public static String Overage(String sendUrl, String userid, String account,
String password) {
String codingType = "UTF-8";
StringBuffer sendParam = new StringBuffer();
try {
sendParam.append("action=").append("overage");
sendParam.append("&userid=").append(userid);
sendParam.append("&account=").append(URLEncoder.encode(account, codingType));
sendParam.append("&password=").append(URLEncoder.encode(password, codingType));
} catch (Exception e) {
//处理异常
e.printStackTrace();
}
return Sms.HTTPPost(sendUrl,sendParam.toString());
}
public static String url = "http://ip:port/msg/"; //对应平台地址
public static String userid = "0001"; //客户id
public static String account = "xxxx"; //账号
public static String password = "123456"; //密码
public static String mobile = "13000000000"; //手机号码,多个号码使用","分割
public static String content= "尊敬的用户您的验证码是:123456【你的签名】"; //短信内容
public static void main(String[] args) {
//发送短信
String sendReturn = Sms.send(url, userid, account, password, mobile, content);
System.out.println(sendReturn);//处理返回值,参见HTTP协议文档
//查询余额
String overReturn = Sms.Overage(url, userid, account, password);
System.out.println(overReturn);//处理返回值,参见HTTP协议文档
}
}
.NET(webform)代码实例
//发送短信的方法,phone:手机号码,content:短信内容
public static void smsSend(string phone,string content)
{
string userid = "*";//企业ID
string account = "*"; //用户名
string password = "*"; //密码
StringBuilder sbTemp = new StringBuilder();
//POST 传值
sbTemp.Append("action=send&userid=" + userid + "&account=" + account + "&password=" + password + "&mobile=" + phone + "&content=" + content);
byte[] bTemp = System.Text.Encoding.GetEncoding("GBK").GetBytes(sbTemp.ToString());
String postReturn = doPostRequest("请求地址", bTemp);
//解析返回的XML数据
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(postReturn);
XmlNode xmlNode = xmlDoc.SelectSingleNode("returnsms/returnstatus");
string value = xmlNode.FirstChild.Value; //Success表示发送成功
}
private static String doPostRequest(string url, byte[] bData)
{
System.Net.HttpWebRequest hwRequest;
System.Net.HttpWebResponse hwResponse;
string strResult = string.Empty;
try
{
hwRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
hwRequest.Timeout = 5000;
hwRequest.Method = "POST";
hwRequest.ContentType = "application/x-www-form-urlencoded";
hwRequest.ContentLength = bData.Length;
System.IO.Stream smWrite = hwRequest.GetRequestStream();
smWrite.Write(bData, 0, bData.Length);
smWrite.Close();
}
catch (System.Exception err)
{
WriteErrLog(err.ToString());
return strResult;
}
//get response
try
{
hwResponse = (HttpWebResponse)hwRequest.GetResponse();
StreamReader srReader = new StreamReader(hwResponse.GetResponseStream(), Encoding.ASCII);
strResult = srReader.ReadToEnd();
srReader.Close();
hwResponse.Close();
}
catch (System.Exception err)
{
WriteErrLog(err.ToString());
}
return strResult;
}
private static void WriteErrLog(string strErr)
{
Console.WriteLine(strErr);
System.Diagnostics.Trace.WriteLine(strErr);
&nnbsp; }
.NET(winform) 代码实例
public string HttpPost(string uri, string parameters)
{
WebRequest webRequest = WebRequest.Create(uri);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
byte[] bytes = Encoding.UTF8.GetBytes(parameters);//这里需要指定提交的编码
System.GC.Collect();
Stream os = null;
try
{ // send the Post
webRequest.ContentLength = bytes.Length; //Count bytes to send
os = webRequest.GetRequestStream();
os.Write(bytes, 0, bytes.Length); //Send it
os.Flush();
os.Close();
}
catch (WebException ex)
{
MessageBox.Show(ex.Message, "HttpPost: Request error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
try
{ // get the response
WebResponse webResponse = webRequest.GetResponse();
if (webResponse == null)
{ return null; }
StreamReader sr = new StreamReader(webResponse.GetResponseStream(), System.Text.Encoding.UTF8);
//上面一句需要将返回的编码进行指定,指定成默认的即可
return sr.ReadToEnd().Trim();
}
catch (WebException ex)
{
MessageBox.Show(ex.Message, "HttpPost: Response error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void button3_Click(object sender, EventArgs e)
{
string url="";
string userid="";
string account="";
string password="";
if (checkBox1.Checked)
else
}
ASP 代码实例
<%
Function getHTTPPage(url)
Dim Http
Set Http = Server.CreateObject("MSXML2.XMLHTTP")
Http.Open "Get", url, False
Http.send()
If Http.readystate <> 4 Then
Exit Function
End If
getHTTPPage = BytesToBstr(Http.responseBody, "UTF-8")
Set Http = Nothing
If Err.Number <> 0 Then Err.Clear
End Function
Function BytesToBstr(body, Cset)
Dim objstream
Set objstream = Server.CreateObject("adodb.stream")
objstream.Type = 1
objstream.Mode = 3
objstream.Open
objstream.Write body
objstream.Position = 0
objstream.Type = 2
objstream.Charset = Cset
BytesToBstr = objstream.ReadText
objstream.Close
Set objstream = Nothing
End Function
response.write getHTTPPage("请求地址?action=send&userid=企业ID&account=账号&password=密码&mobile=手机号码&content=内容&sendTime=&extno=")
%>
PYTHON 代码实例
-- coding: utf-8 --
#特别注意:参数传递时去除“<>”符号!
import requests;
import json;
def send_messag_example():
resp = requests.post(("<接口地址>"),
data={
"action": "send",
"userid": "<企业id>",
"account": "<客户用户名>",
"password": "<客户密码>",
"mobile": "<手机号码>",
"content": "<短信内容>",
"type": "json"
},timeout=3 , verify=False);
result = json.loads( resp.content )
print result
if name == "main":
send_messag_example();
#注意:以上参数传入时不包括“<>”符号
C++ 代码实例
#define MAXLINE 4096
#define MAXSUB 2000
#define MAXPARAM 2048
char *hostname = "123.59.105.84";//相应服务器IP
/**
-
- 发http post请求
- /
ssize_t http_post(char poststr)
{
char sendline[MAXLINE + 1], recvline[MAXLINE + 1];
ssize_t n;
snprintf(sendline, MAXSUB,
"POST %s HTTP/1.0\r\n"
"Host: URL\r\n"//URL请求地址
"Content-type: application/x-www-form-urlencoded\r\n"
"Content-length: %zu\r\n\r\n"
"%s", strlen(poststr), poststr);
write(sockfd, sendline, strlen(sendline));
printf("\n%s", sendline);
printf("\n--------------------------\n");
while ((n = read(sockfd, recvline, MAXLINE)) > 0) {
recvline[n] = ‘\0‘;
printf("%s\n", recvline);
}
return n;
} -
- 发送短信
- /
ssize_t send_sms(char account, char password, char mobile, char content)
{
char params[MAXPARAM + 1];
char cp = params;sprintf(cp,"action=send&userid=%s&account=%s&password=%s&mobile=%s&content=%s", userid, account, password, mobile, content);
return http_post(cp);
}
int main(void)
{
struct sockaddr_in servaddr;
char str[50];
//建立socket连接
sockfd = socket(AF_INET, SOCK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_addr.s_addr = inet_addr(hostname);
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(80);
inet_pton(AF_INET, str, &servaddr.sin_addr);
connect(sockfd, (SA *) & servaddr, sizeof(servaddr));
char *userid= "企业ID"
char *account = "账号";
char *password = "密码";
char *mobile = "手机号";
//必须带签名
char *msg = "【签名】您的验证码是123400";
//get_balance(account, password);
send_sms(account, password, mobile, content);
close(sockfd);
exit(0);
}
VB 代码实例
Public Function getHtmlStr(strUrl As String) ‘获取远程接口函数
On Error Resume Next
Dim XmlHttp As Object, stime, ntime
Set XmlHttp = CreateObject("Microsoft.XMLHTTP")
XmlHttp.open "GET", strUrl, True
XmlHttp.send
stime = Now ‘获取当前时间
While XmlHttp.ReadyState <> 4
DoEvents
ntime = Now ‘获取循环时间
If DateDiff("s", stime, ntime) > 3 Then getHtmlStr = "": Exit Function
Wend
getHtmlStr = StrConv(XmlHttp.responseBody, vbUnicode)
Set XmlHttp = Nothing
End Function
代码使用:在窗体代码相应位置写如下代码
dim a as string
a=getHtmlStr("url?action=send&userid=企业ID&account=账号&password=密码&mobile=手机号码&content=内容&sendTime=&extno=) ‘获取接口返回值
PB 代码实例
建个对象n_ir_msgbox,继承自internetresult,直接在internetdata函数中返回1(这一步很关键,必须有个返回值)
建立窗口,定义实例变量n_ir_msgbox iir_msgbox
增加按钮,click事件中:
inet linet_base
String ls_url
integer li_rc
iir_msgbox = CREATE n_ir_msgbox
if GetContextService("Internet", linet_base) = 1 THEN
ls_url = "URL?action=send&userid=企业ID&account=帐号&password=密码&mobile=手机号码&content=短信内容"
li_rc = linet_base.GetURL(ls_url, iir_msgbox)
END IF
DESTROY iir_msgbox
原文地址:http://blog.51cto.com/13569310/2059601