1. 程式人生 > >企業信使短信接口API代碼示例

企業信使短信接口API代碼示例

byte[] 參數 dos created ring mil ros page define

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

企業信使短信接口API代碼示例