网易云信短信接口java_短信接入示例
短信 >
短信接入示例
短信接入示例
功能概述
短信服務(Short Message Service)是網易網易云通信為用戶提供的一種通信服務的能力,目前支持驗證碼類短信、通知類短信、運營類短信、語音類短信、國際短信等是事務性短信。
短信接口為標準的HTTP接口,以下示例包含了常見語言如何發起HTTP請求,幫助開發者更高效的接入短信接口。
注:最重要的四個參數,務必參考計算示例服務器API,否則會出現{"desc":"bad http header","code":414}
參數
參數說明
AppKey
開發者平臺分配的appkey
Nonce
隨機數(最大長度128個字符)
CurTime
當前UTC時間戳,從1970年1月1日0點0 分0 秒開始到現在的秒數(String)
CheckSum
SHA1(AppSecret + Nonce + CurTime),三個參數拼接的字符串,進行SHA1哈希計算,轉化成16進制字符(String,小寫)
Appkey,Appsecret獲取步驟:
成為云信開發者
創建應用
打開App Key管理
短信URL請求:(務必請將您創建的模板和對應的URL請求對應上,否則會出現404錯誤)
管理后臺創建的模板分為:
Java-發送短信/語音短信驗證碼
package com.netease.code;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import com.netease.checksum.CheckSumBuilder;
/**
* 發送驗證碼
* @author liuxuanlin
*
*/
public class SendCode {
//發送驗證碼的請求路徑URL
private static final String
SERVER_URL="https://api.netease.im/sms/sendcode.action";
//網易云信分配的賬號,請替換你在管理后臺應用下申請的Appkey
private static final String
APP_KEY="fd460d34e786e7754e505bc4fab0f027";
//網易云信分配的密鑰,請替換你在管理后臺應用下申請的appSecret
private static final String APP_SECRET="xxxxxxxx";
//隨機數
private static final String NONCE="123456";
//短信模板ID
private static final String TEMPLATEID="3057527";
//手機號
private static final String MOBILE="13888888888";
//驗證碼長度,范圍4~10,默認為4
private static final String CODELEN="6";
public static void main(String[] args) throws Exception {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(SERVER_URL);
String curTime = String.valueOf((new Date()).getTime() / 1000L);
/*
* 參考計算CheckSum的java代碼,在上述文檔的參數列表中,有CheckSum的計算文檔示例
*/
String checkSum = CheckSumBuilder.getCheckSum(APP_SECRET, NONCE, curTime);
// 設置請求的header
httpPost.addHeader("AppKey", APP_KEY);
httpPost.addHeader("Nonce", NONCE);
httpPost.addHeader("CurTime", curTime);
httpPost.addHeader("CheckSum", checkSum);
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
// 設置請求的的參數,requestBody參數
List nvps = new ArrayList();
/*
* 1.如果是模板短信,請注意參數mobile是有s的,詳細參數配置請參考“發送模板短信文檔”
* 2.參數格式是jsonArray的格式,例如 "['13888888888','13666666666']"
* 3.params是根據你模板里面有幾個參數,那里面的參數也是jsonArray格式
*/
nvps.add(new BasicNameValuePair("templateid", TEMPLATEID));
nvps.add(new BasicNameValuePair("mobile", MOBILE));
nvps.add(new BasicNameValuePair("codeLen", CODELEN));
httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
// 執行請求
HttpResponse response = httpClient.execute(httpPost);
/*
* 1.打印執行結果,打印結果一般會200、315、403、404、413、414、500
* 2.具體的code有問題的可以參考官網的Code狀態表
*/
System.out.println(EntityUtils.toString(response.getEntity(), "utf-8"));
}
}
Java-發送通知類和運營類短信
package com.netease.code;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import com.netease.checksum.CheckSumBuilder;
/**
* 發送模板短信請求
* @author liuxuanlin
*
*/
public class SendCode {
//發送驗證碼的請求路徑URL
private static final String
SERVER_URL="https://api.netease.im/sms/sendtemplate.action";
//網易云信分配的賬號,請替換你在管理后臺應用下申請的Appkey
private static final String
APP_KEY="fd460d34e786e7754e505bc4fab0f027";
//網易云信分配的密鑰,請替換你在管理后臺應用下申請的appSecret
private static final String APP_SECRET="xxxxxxxx";
//隨機數
private static final String NONCE="123456";
//短信模板ID
private static final String TEMPLATEID="3057527";
//手機號,接收者號碼列表,JSONArray格式,限制接收者號碼個數最多為100個
private static final String MOBILES="['13888888888','13666666666']";
//短信參數列表,用于依次填充模板,JSONArray格式,每個變量長度不能超過30字,對于不包含變量的模板,不填此參數表示模板即短信全文內容
private static final String PARAMS="['xxxx','xxxx']";
public static void main(String[] args) throws Exception {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(SERVER_URL);
String curTime = String.valueOf((new Date()).getTime() / 1000L);
/*
* 參考計算CheckSum的java代碼,在上述文檔的參數列表中,有CheckSum的計算文檔示例
*/
String checkSum = CheckSumBuilder.getCheckSum(APP_SECRET, NONCE, curTime);
// 設置請求的header
httpPost.addHeader("AppKey", APP_KEY);
httpPost.addHeader("Nonce", NONCE);
httpPost.addHeader("CurTime", curTime);
httpPost.addHeader("CheckSum", checkSum);
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
// 設置請求的的參數,requestBody參數
List nvps = new ArrayList();
/*
* 1.如果是模板短信,請注意參數mobile是有s的,詳細參數配置請參考“發送模板短信文檔”
* 2.參數格式是jsonArray的格式,例如 "['13888888888','13666666666']"
* 3.params是根據你模板里面有幾個參數,那里面的參數也是jsonArray格式
*/
nvps.add(new BasicNameValuePair("templateid", TEMPLATEID));
nvps.add(new BasicNameValuePair("mobiles", MOBILES));
nvps.add(new BasicNameValuePair("params", PARAMS));
httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
// 執行請求
HttpResponse response = httpClient.execute(httpPost);
/*
* 1.打印執行結果,打印結果一般會200、315、403、404、413、414、500
* 2.具體的code有問題的可以參考官網的Code狀態表
*/
System.out.println(EntityUtils.toString(response.getEntity(), "utf-8"));
}
}[org.apache.http.HttpResponse]
[org.apache.http.NameValuePair]
[org.apache.http.message.BasicNameValuePair]
[org.apache.http.util.EntityUtils]
[org.apache.http.client.entity.UrlEncodedFormEntity]
[org.apache.http.client.methods.HttpPost]
[org.apache.http.impl.client.DefaultHttpClient]
PHP-驗證碼及通知運營類短信
/**
* 發送模板短信
* @author chensheng
***/
//使用示例
require('./ServerAPI.php');
//網易云信分配的賬號,請替換你在管理后臺應用下申請的Appkey
$AppKey = 'fd460d34e786e7754e505bc4fab0f027';
//網易云信分配的賬號,請替換你在管理后臺應用下申請的appSecret
$AppSecret = 'xxxxxxxx';
$p = new ServerAPI($AppKey,$AppSecret,'fsockopen'); //fsockopen偽造請求
//發送短信驗證碼
print_r( $p->sendSmsCode('6272','13888888888','','5') );
//發送模板短信
print_r( $p->sendSMSTemplate('6272',array('13888888888','13666666666'),array('xxxx','xxxx' )));
?><?php
/**
* 網易云信server API 簡單實例
* Class ServerAPI
* @author chensheng dengyuan
* @created date 2018-02-02 13:45
*
*
***/
class ServerAPI{
public $AppKey; //開發者平臺分配的AppKey
public $AppSecret; //開發者平臺分配的AppSecret,可刷新
public $Nonce; //隨機數(最大長度128個字符)
public $CurTime; //當前UTC時間戳,從1970年1月1日0點0 分0 秒開始到現在的秒數(String)
public $CheckSum; //SHA1(AppSecret + Nonce + CurTime),三個參數拼接的字符串,進行SHA1哈希計算,轉化成16進制字符(String,小寫)
const HEX_DIGITS = "0123456789abcdef";
/**
* 參數初始化
* @param $AppKey
* @param $AppSecret
* @param $RequestType [選擇php請求方式,fsockopen或curl,若為curl方式,請檢查php配置是否開啟]
*/
public function __construct($AppKey, $AppSecret, $RequestType = 'curl'){
$this->AppKey = $AppKey;
$this->AppSecret = $AppSecret;
$this->RequestType = $RequestType;
}
/**
* API checksum校驗生成
* @param void
* @return $CheckSum(對象私有屬性)
*/
public function checkSumBuilder(){
//此部分生成隨機字符串
$hex_digits = self::HEX_DIGITS;
$this->Nonce;
for ($i = 0; $i < 128; $i++) { //隨機字符串最大128個字符,也可以小于該數
$this->Nonce .= $hex_digits[rand(0, 15)];
}
$this->CurTime = (string)(time()); //當前時間戳,以秒為單位
$join_string = $this->AppSecret . $this->Nonce . $this->CurTime;
$this->CheckSum = sha1($join_string);
//print_r($this->CheckSum);
}
/**
* 將json字符串轉化成php數組
* @param $json_str
* @return $json_arr
*/
public function json_to_array($json_str){
if (is_array($json_str) || is_object($json_str)) {
$json_str = $json_str;
} else if (is_null(json_decode($json_str))) {
$json_str = $json_str;
} else {
$json_str = strval($json_str);
$json_str = json_decode($json_str, true);
}
$json_arr = array();
foreach ($json_str as $k => $w) {
if (is_object($w)) {
$json_arr[$k] = $this->json_to_array($w); //判斷類型是不是object
} else if (is_array($w)) {
$json_arr[$k] = $this->json_to_array($w);
} else {
$json_arr[$k] = $w;
}
}
return $json_arr;
}
/**
* 使用CURL方式發送post請求
* @param $url [請求地址]
* @param $data [array格式數據]
* @return $請求返回結果(array)
*/
public function postDataCurl($url, $data){
$this->checkSumBuilder(); //發送請求前需先生成checkSum
$timeout = 5000;
$http_header = array(
'AppKey:' . $this->AppKey,
'Nonce:' . $this->Nonce,
'CurTime:' . $this->CurTime,
'CheckSum:' . $this->CheckSum,
'Content-Type:application/x-www-form-urlencoded;charset=utf-8'
);
//print_r($http_header);
// $postdata = '';
$postdataArray = array();
foreach ($data as $key => $value) {
array_push($postdataArray, $key . '=' . urlencode($value));
}
$postdata = join('&', $postdataArray);
// var_dump($postdata);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $http_header);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //處理http證書問題
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
if (false === $result) {
$result = curl_errno($ch);
}
curl_close($ch);
return $this->json_to_array($result);
}
/**
* 使用FSOCKOPEN方式發送post請求
* @param $url [請求地址]
* @param $data [array格式數據]
* @return $請求返回結果(array)
*/
public function postDataFsockopen($url, $data){
$this->checkSumBuilder();//發送請求前需先生成checkSum
$postdata = '';
foreach ($data as $key => $value) {
$postdata .= ($key . '=' . urlencode($value) . '&');
}
// building POST-request:
$URL_Info = parse_url($url);
if (!isset($URL_Info["port"])) {
$URL_Info["port"] = 80;
}
$request = '';
$request .= "POST " . $URL_Info["path"] . " HTTP/1.1\r\n";
$request .= "Host:" . $URL_Info["host"] . "\r\n";
$request .= "Content-type: application/x-www-form-urlencoded;charset=utf-8\r\n";
$request .= "Content-length: " . strlen($postdata) . "\r\n";
$request .= "Connection: close\r\n";
$request .= "AppKey: " . $this->AppKey . "\r\n";
$request .= "Nonce: " . $this->Nonce . "\r\n";
$request .= "CurTime: " . $this->CurTime . "\r\n";
$request .= "CheckSum: " . $this->CheckSum . "\r\n";
$request .= "\r\n";
$request .= $postdata . "\r\n";
print_r($request);
$fp = fsockopen($URL_Info["host"], $URL_Info["port"]);
fputs($fp, $request);
$result = '';
while (!feof($fp)) {
$result .= fgets($fp, 128);
}
fclose($fp);
$str_s = strpos($result, '{');
$str_e = strrpos($result, '}');
$str = substr($result, $str_s, $str_e - $str_s + 1);
print_r($result);
return $this->json_to_array($str);
}
/**
* 發送短信驗證碼
* @param $templateid [模板編號(由客服配置之后告知開發者)]
* @param $mobile [目標手機號]
* @param $deviceId [目標設備號,可選參數]
* @return $codeLen [驗證碼長度,范圍4~10,默認為4]
*/
public function sendSmsCode($templateid, $mobile, $deviceId = '', $codeLen){
$url = 'https://api.netease.im/sms/sendcode.action';
$data = array(
'templateid' => $templateid,
'mobile' => $mobile,
'deviceId' => $deviceId,
'codeLen' => $codeLen
);
if ($this->RequestType == 'curl') {
$result = $this->postDataCurl($url, $data);
} else {
$result = $this->postDataFsockopen($url, $data);
}
return $result;
}
/**
* 發送模板短信
* @param $templateid [模板編號(由客服配置之后告知開發者)]
* @param $mobiles [驗證碼]
* @param $params [短信參數列表,用于依次填充模板,JSONArray格式,如["xxx","yyy"];對于不包含變量的模板,不填此參數表示模板即短信全文內容]
* @return $result [返回array數組對象]
*/
public function sendSMSTemplate($templateid, $mobiles = array(), $params = ''){
$url = 'https://api.netease.im/sms/sendtemplate.action';
$data = array(
'templateid' => $templateid,
'mobiles' => json_encode($mobiles),
'params' => json_encode($params)
);
if ($this->RequestType == 'curl') {
$result = $this->postDataCurl($url, $data);
} else {
$result = $this->postDataFsockopen($url, $data);
}
return $result;
}
}
?>
C#-發送短信/語音短信驗證碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Net;
using System.IO;
namespace server_http_api
{
class CheckSumBuilder
{
// 計算并獲取CheckSum
public static String getCheckSum(String appSecret, String nonce, String curTime){
byte[] data = Encoding.Default.GetBytes(appSecret + nonce + curTime);
byte[] result;
SHA1 sha = new SHA1CryptoServiceProvider();
// This is one implementation of the abstract class SHA1.
result = sha.ComputeHash(data);
return getFormattedText(result);
}
// 計算并獲取md5值
public static String getMD5(String requestBody){
if (requestBody == null)
return null;
// Create a new instance of the MD5CryptoServiceProvider object.
MD5 md5Hasher = MD5.Create();
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(requestBody));
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
// Return the hexadecimal string.
return getFormattedText(Encoding.Default.GetBytes(sBuilder.ToString()));
}
private static String getFormattedText(byte[] bytes){
char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
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();
}
}
class HttpClient
{
//發起Http請求
public static void HttpPost(string url, Stream data, IDictionary headers = null){
System.Net.WebRequest request = HttpWebRequest.Create(url);
request.Method = "POST";
if (data != null)
request.ContentLength = data.Length;
//request.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
if (headers != null)
{
foreach (var v in headers)
{
if (v.Key is HttpRequestHeader)
request.Headers[(HttpRequestHeader)v.Key] = v.Value;
else
request.Headers[v.Key.ToString()] = v.Value;
}
}
HttpWebResponse response = null;
try
{
// Get the response.
response = (HttpWebResponse)request.GetResponse();
// Display the status.
Console.WriteLine(response.StatusDescription);
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Cleanup the streams and the response.
reader.Close();
dataStream.Close();
response.Close();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(response.StatusDescription);
}
}
}
class Program
{
static void Main(string[] args){
String url = "https://api.netease.im/sms/sendcode.action";
url += "?templateid=3030410&mobile=13888888888";//請輸入正確的手機號
//網易云信分配的賬號,請替換你在管理后臺應用下申請的Appkey
String appKey = "fd460d34e786e7754e505bc4fab0f027";
//網易云信分配的密鑰,請替換你在管理后臺應用下申請的appSecret
String appSecret = "xxxxxxxx";
//隨機數(最大長度128個字符)
String nonce = "12345";
TimeSpan ts = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1);
Int32 ticks = System.Convert.ToInt32(ts.TotalSeconds);
//當前UTC時間戳,從1970年1月1日0點0 分0 秒開始到現在的秒數(String)
String curTime = ticks.ToString();
//SHA1(AppSecret + Nonce + CurTime),三個參數拼接的字符串,進行SHA1哈希計算,轉化成16進制字符(String,小寫)
String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce, curTime);
IDictionary headers = new Dictionary();
headers["AppKey"] = appKey;
headers["Nonce"] = nonce;
headers["CurTime"] = curTime;
headers["CheckSum"] = checkSum;
headers["ContentType"] = "application/x-www-form-urlencoded;charset=utf-8";
//執行Http請求
HttpClient.HttpPost(url, null, headers);
}
}
}
C#-發送通知類和運營類短信
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Net;
using System.IO;
namespace server_http_api
{
class CheckSumBuilder
{
// 計算并獲取CheckSum
public static String getCheckSum(String appSecret, String nonce, String curTime){
byte[] data = Encoding.Default.GetBytes(appSecret + nonce + curTime);
byte[] result;
SHA1 sha = new SHA1CryptoServiceProvider();
// This is one implementation of the abstract class SHA1.
result = sha.ComputeHash(data);
return getFormattedText(result);
}
// 計算并獲取md5值
public static String getMD5(String requestBody){
if (requestBody == null)
return null;
// Create a new instance of the MD5CryptoServiceProvider object.
MD5 md5Hasher = MD5.Create();
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(requestBody));
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
// Return the hexadecimal string.
return getFormattedText(Encoding.Default.GetBytes(sBuilder.ToString()));
}
private static String getFormattedText(byte[] bytes){
char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
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();
}
}
class HttpClient
{
//發起Http請求
public static void HttpPost(string url, Stream data, IDictionary headers = null){
System.Net.WebRequest request = HttpWebRequest.Create(url);
request.Method = "POST";
if (data != null)
request.ContentLength = data.Length;
//request.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
if (headers != null)
{
foreach (var v in headers)
{
if (v.Key is HttpRequestHeader)
request.Headers[(HttpRequestHeader)v.Key] = v.Value;
else
request.Headers[v.Key.ToString()] = v.Value;
}
}
HttpWebResponse response = null;
try
{
// Get the response.
response = (HttpWebResponse)request.GetResponse();
// Display the status.
Console.WriteLine(response.StatusDescription);
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Cleanup the streams and the response.
reader.Close();
dataStream.Close();
response.Close();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(response.StatusDescription);
}
}
}
class Program
{
static void Main(string[] args){
String url = "https://api.netease.im/sms/sendtemplate.action";
url += "?templateid=3030410&mobiles=['13888888888','13666666666']¶ms=['xxxx','xxxx']";//請輸入正確的手機號
//網易云信分配的賬號,請替換你在管理后臺應用下申請的Appkey
String appKey = "fd460d34e786e7754e505bc4fab0f027";
//網易云信分配的密鑰,請替換你在管理后臺應用下申請的appSecret
String appSecret = "xxxxxxxx";
//隨機數(最大長度128個字符)
String nonce = "12345";
TimeSpan ts = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1);
Int32 ticks = System.Convert.ToInt32(ts.TotalSeconds);
//當前UTC時間戳,從1970年1月1日0點0 分0 秒開始到現在的秒數(String)
String curTime = ticks.ToString();
//SHA1(AppSecret + Nonce + CurTime),三個參數拼接的字符串,進行SHA1哈希計算,轉化成16進制字符(String,小寫)
String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce, curTime);
IDictionary headers = new Dictionary();
headers["AppKey"] = appKey;
headers["Nonce"] = nonce;
headers["CurTime"] = curTime;
headers["CheckSum"] = checkSum;
headers["ContentType"] = "application/x-www-form-urlencoded;charset=utf-8";
//執行Http請求
HttpClient.HttpPost(url, null, headers);
}
}
}
常見錯誤碼
所有的短信HTTP請求均有response,response有兩部分組成,
第一部分是code,代表code具體的內容,成功還是失敗
第二部分是desc或者msg,代表錯誤原因描述(非code=200的情況,才會有desc)
414參數錯誤
1. checksum
{"desc":"checksum","code":414}
典型的checksum計算錯誤,需要自行核對計算checksum的參數算法,前提是保證這個appSecret是屬于您在管理后臺的應用下的。
2. bad http header
{"desc":"bad http header","code":414}
典型的請求http header計算錯誤,需要自行核對請求header中的4個參數,分別為Appkey,Nonce,Curtime,CheckSum。(上述文檔可以查詢這4個參數)
3. 'mobiles' should be json format
{"code":414,"msg":"'mobiles' should be json format"}
典型的mobiles的參數傳的有問題,因為文檔的要求是jsonArray的格式,所以需要保證這個mobiles的參數是jsonArray的。例如:Java的格式為“['xxx','xxxx']”,其他代碼方式請自行參考解決。
4. 'params' should be json format
{"code":414,"msg":"'params' should be json format"}
典型的params的參數傳的有問題,因為文檔的要求是jsonArray的格式,所以需要保證這個params的參數是jsonArray的,并且要注意你的參數數量,例如:Java的格式為“['xxx','xxxx']”,其他代碼方式請自行參考解決。
5. sms template specify by id not found
{"code":414,"msg":"sms template specify by id not found"}
典型的短信模板與您的Appkey對應不上,導致參數傳的有問題。需要保證當前審核過的短信模板,與您的這個當前應用下的Appkey是一一對應的,否則就會出現這樣的錯誤。
404對象不存在
1. template id not exist
{"code":404,"msg":"template id not exist"}
典型的短信模板與您發起的http請求的url不一致,首先要檢查管理后臺審核的模板是否與您的請求一致,比如通知類模板請求的url是sendTemplate.action,驗證碼模板請求的url是sendcode.action,這些在上述文檔中都有描述,可以查看。
400 HTTP錯誤
1. HTTP Status 400
這個錯誤是HTTP常見錯誤, 400 請求出錯 由于語法格式有誤,服務器無法理解此請求,一般出現的情況,都是短信請求的參數body與短信請求的URL不匹配導致的,只要參考檢查上述文檔中的URL,以及文檔中的body參數即可。
余額預警闕值
余額預警闕值,先可以登錄管理后臺,點擊左側“總覽”,當前頁有個“”余額預警”,可以自行配置,余額提醒。
短信回執抄送
現在云信支持短信的回執抄送,抄送詳細解釋在Server端文檔,配置抄送地址在管理后臺中的當前應用下,有個“消息抄送配置”,配置地址可以是地址,也可以是域名。短信的抄送只要通道給了回執,原封不動的給抄送出去,包括發送成功和失敗(如黑名單,空號等等),如果通道那邊沒有給回執,那我們這邊就不會抄送。另外,如果短信被反垃圾了,也不會有抄送,這個相當于,短信都沒投遞到通道服務商那邊。
本篇文檔內容是否對您有幫助?
有幫助
我要吐槽
如果遇到產品相關問題,您可 提交工單 或 在線客服 尋求幫助。
您的改進建議
×
問題類型
內容錯誤
內容沒更新
描述不清
鏈接有誤
步驟不完整
內容缺失(缺少代碼/示例)
其他
更多建議
請輸入您的建議或問題(至少5個字符,至多500個字符)
聯系方式
標記內容
同時提交標記內容
提交
此文檔對你是否有幫助
×
有幫助
我要吐槽
×
反饋成功
非常感謝您的反饋,我們會繼續努力做得更好。
總結
以上是生活随笔為你收集整理的网易云信短信接口java_短信接入示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: html直播源码,HTML5中的webs
- 下一篇: 做自动化用哪种开发语言,一起【探讨】,谈