日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

网易云信短信接口java_短信接入示例

發(fā)布時間:2023/12/20 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 网易云信短信接口java_短信接入示例 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

短信 >

短信接入示例

短信接入示例

功能概述

短信服務(wù)(Short Message Service)是網(wǎng)易網(wǎng)易云通信為用戶提供的一種通信服務(wù)的能力,目前支持驗證碼類短信、通知類短信、運(yùn)營類短信、語音類短信、國際短信等是事務(wù)性短信。

短信接口為標(biāo)準(zhǔn)的HTTP接口,以下示例包含了常見語言如何發(fā)起HTTP請求,幫助開發(fā)者更高效的接入短信接口。

注:最重要的四個參數(shù),務(wù)必參考計算示例服務(wù)器API,否則會出現(xiàn){"desc":"bad http header","code":414}

參數(shù)

參數(shù)說明

AppKey

開發(fā)者平臺分配的appkey

Nonce

隨機(jī)數(shù)(最大長度128個字符)

CurTime

當(dāng)前UTC時間戳,從1970年1月1日0點(diǎn)0 分0 秒開始到現(xiàn)在的秒數(shù)(String)

CheckSum

SHA1(AppSecret + Nonce + CurTime),三個參數(shù)拼接的字符串,進(jìn)行SHA1哈希計算,轉(zhuǎn)化成16進(jìn)制字符(String,小寫)

Appkey,Appsecret獲取步驟:

成為云信開發(fā)者

創(chuàng)建應(yīng)用

打開App Key管理

短信URL請求:(務(wù)必請將您創(chuàng)建的模板和對應(yīng)的URL請求對應(yīng)上,否則會出現(xiàn)404錯誤)

管理后臺創(chuàng)建的模板分為:

Java-發(fā)送短信/語音短信驗證碼

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;

/**

* 發(fā)送驗證碼

* @author liuxuanlin

*

*/

public class SendCode {

//發(fā)送驗證碼的請求路徑URL

private static final String

SERVER_URL="https://api.netease.im/sms/sendcode.action";

//網(wǎng)易云信分配的賬號,請?zhí)鎿Q你在管理后臺應(yīng)用下申請的Appkey

private static final String

APP_KEY="fd460d34e786e7754e505bc4fab0f027";

//網(wǎng)易云信分配的密鑰,請?zhí)鎿Q你在管理后臺應(yīng)用下申請的appSecret

private static final String APP_SECRET="xxxxxxxx";

//隨機(jī)數(shù)

private static final String NONCE="123456";

//短信模板ID

private static final String TEMPLATEID="3057527";

//手機(jī)號

private static final String MOBILE="13888888888";

//驗證碼長度,范圍4~10,默認(rèn)為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代碼,在上述文檔的參數(shù)列表中,有CheckSum的計算文檔示例

*/

String checkSum = CheckSumBuilder.getCheckSum(APP_SECRET, NONCE, curTime);

// 設(shè)置請求的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");

// 設(shè)置請求的的參數(shù),requestBody參數(shù)

List nvps = new ArrayList();

/*

* 1.如果是模板短信,請注意參數(shù)mobile是有s的,詳細(xì)參數(shù)配置請參考“發(fā)送模板短信文檔”

* 2.參數(shù)格式是jsonArray的格式,例如 "['13888888888','13666666666']"

* 3.params是根據(jù)你模板里面有幾個參數(shù),那里面的參數(shù)也是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"));

// 執(zhí)行請求

HttpResponse response = httpClient.execute(httpPost);

/*

* 1.打印執(zhí)行結(jié)果,打印結(jié)果一般會200、315、403、404、413、414、500

* 2.具體的code有問題的可以參考官網(wǎng)的Code狀態(tài)表

*/

System.out.println(EntityUtils.toString(response.getEntity(), "utf-8"));

}

}

Java-發(fā)送通知類和運(yùn)營類短信

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;

/**

* 發(fā)送模板短信請求

* @author liuxuanlin

*

*/

public class SendCode {

//發(fā)送驗證碼的請求路徑URL

private static final String

SERVER_URL="https://api.netease.im/sms/sendtemplate.action";

//網(wǎng)易云信分配的賬號,請?zhí)鎿Q你在管理后臺應(yīng)用下申請的Appkey

private static final String

APP_KEY="fd460d34e786e7754e505bc4fab0f027";

//網(wǎng)易云信分配的密鑰,請?zhí)鎿Q你在管理后臺應(yīng)用下申請的appSecret

private static final String APP_SECRET="xxxxxxxx";

//隨機(jī)數(shù)

private static final String NONCE="123456";

//短信模板ID

private static final String TEMPLATEID="3057527";

//手機(jī)號,接收者號碼列表,JSONArray格式,限制接收者號碼個數(shù)最多為100個

private static final String MOBILES="['13888888888','13666666666']";

//短信參數(shù)列表,用于依次填充模板,JSONArray格式,每個變量長度不能超過30字,對于不包含變量的模板,不填此參數(shù)表示模板即短信全文內(nèi)容

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代碼,在上述文檔的參數(shù)列表中,有CheckSum的計算文檔示例

*/

String checkSum = CheckSumBuilder.getCheckSum(APP_SECRET, NONCE, curTime);

// 設(shè)置請求的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");

// 設(shè)置請求的的參數(shù),requestBody參數(shù)

List nvps = new ArrayList();

/*

* 1.如果是模板短信,請注意參數(shù)mobile是有s的,詳細(xì)參數(shù)配置請參考“發(fā)送模板短信文檔”

* 2.參數(shù)格式是jsonArray的格式,例如 "['13888888888','13666666666']"

* 3.params是根據(jù)你模板里面有幾個參數(shù),那里面的參數(shù)也是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"));

// 執(zhí)行請求

HttpResponse response = httpClient.execute(httpPost);

/*

* 1.打印執(zhí)行結(jié)果,打印結(jié)果一般會200、315、403、404、413、414、500

* 2.具體的code有問題的可以參考官網(wǎng)的Code狀態(tài)表

*/

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-驗證碼及通知運(yùn)營類短信

/**

* 發(fā)送模板短信

* @author chensheng

***/

//使用示例

require('./ServerAPI.php');

//網(wǎng)易云信分配的賬號,請?zhí)鎿Q你在管理后臺應(yīng)用下申請的Appkey

$AppKey = 'fd460d34e786e7754e505bc4fab0f027';

//網(wǎng)易云信分配的賬號,請?zhí)鎿Q你在管理后臺應(yīng)用下申請的appSecret

$AppSecret = 'xxxxxxxx';

$p = new ServerAPI($AppKey,$AppSecret,'fsockopen'); //fsockopen偽造請求

//發(fā)送短信驗證碼

print_r( $p->sendSmsCode('6272','13888888888','','5') );

//發(fā)送模板短信

print_r( $p->sendSMSTemplate('6272',array('13888888888','13666666666'),array('xxxx','xxxx' )));

?><?php

/**

* 網(wǎng)易云信server API 簡單實例

* Class ServerAPI

* @author chensheng dengyuan

* @created date 2018-02-02 13:45

*

*

***/

class ServerAPI{

public $AppKey; //開發(fā)者平臺分配的AppKey

public $AppSecret; //開發(fā)者平臺分配的AppSecret,可刷新

public $Nonce; //隨機(jī)數(shù)(最大長度128個字符)

public $CurTime; //當(dāng)前UTC時間戳,從1970年1月1日0點(diǎn)0 分0 秒開始到現(xiàn)在的秒數(shù)(String)

public $CheckSum; //SHA1(AppSecret + Nonce + CurTime),三個參數(shù)拼接的字符串,進(jìn)行SHA1哈希計算,轉(zhuǎn)化成16進(jìn)制字符(String,小寫)

const HEX_DIGITS = "0123456789abcdef";

/**

* 參數(shù)初始化

* @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(){

//此部分生成隨機(jī)字符串

$hex_digits = self::HEX_DIGITS;

$this->Nonce;

for ($i = 0; $i < 128; $i++) { //隨機(jī)字符串最大128個字符,也可以小于該數(shù)

$this->Nonce .= $hex_digits[rand(0, 15)];

}

$this->CurTime = (string)(time()); //當(dāng)前時間戳,以秒為單位

$join_string = $this->AppSecret . $this->Nonce . $this->CurTime;

$this->CheckSum = sha1($join_string);

//print_r($this->CheckSum);

}

/**

* 將json字符串轉(zhuǎn)化成php數(shù)組

* @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方式發(fā)送post請求

* @param $url [請求地址]

* @param $data [array格式數(shù)據(jù)]

* @return $請求返回結(jié)果(array)

*/

public function postDataCurl($url, $data){

$this->checkSumBuilder(); //發(fā)送請求前需先生成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方式發(fā)送post請求

* @param $url [請求地址]

* @param $data [array格式數(shù)據(jù)]

* @return $請求返回結(jié)果(array)

*/

public function postDataFsockopen($url, $data){

$this->checkSumBuilder();//發(fā)送請求前需先生成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);

}

/**

* 發(fā)送短信驗證碼

* @param $templateid [模板編號(由客服配置之后告知開發(fā)者)]

* @param $mobile [目標(biāo)手機(jī)號]

* @param $deviceId [目標(biāo)設(shè)備號,可選參數(shù)]

* @return $codeLen [驗證碼長度,范圍4~10,默認(rèn)為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;

}

/**

* 發(fā)送模板短信

* @param $templateid [模板編號(由客服配置之后告知開發(fā)者)]

* @param $mobiles [驗證碼]

* @param $params [短信參數(shù)列表,用于依次填充模板,JSONArray格式,如["xxx","yyy"];對于不包含變量的模板,不填此參數(shù)表示模板即短信全文內(nèi)容]

* @return $result [返回array數(shù)組對象]

*/

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#-發(fā)送短信/語音短信驗證碼

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

{

//發(fā)起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";//請輸入正確的手機(jī)號

//網(wǎng)易云信分配的賬號,請?zhí)鎿Q你在管理后臺應(yīng)用下申請的Appkey

String appKey = "fd460d34e786e7754e505bc4fab0f027";

//網(wǎng)易云信分配的密鑰,請?zhí)鎿Q你在管理后臺應(yīng)用下申請的appSecret

String appSecret = "xxxxxxxx";

//隨機(jī)數(shù)(最大長度128個字符)

String nonce = "12345";

TimeSpan ts = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1);

Int32 ticks = System.Convert.ToInt32(ts.TotalSeconds);

//當(dāng)前UTC時間戳,從1970年1月1日0點(diǎn)0 分0 秒開始到現(xiàn)在的秒數(shù)(String)

String curTime = ticks.ToString();

//SHA1(AppSecret + Nonce + CurTime),三個參數(shù)拼接的字符串,進(jìn)行SHA1哈希計算,轉(zhuǎn)化成16進(jìn)制字符(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";

//執(zhí)行Http請求

HttpClient.HttpPost(url, null, headers);

}

}

}

C#-發(fā)送通知類和運(yùn)營類短信

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

{

//發(fā)起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']&params=['xxxx','xxxx']";//請輸入正確的手機(jī)號

//網(wǎng)易云信分配的賬號,請?zhí)鎿Q你在管理后臺應(yīng)用下申請的Appkey

String appKey = "fd460d34e786e7754e505bc4fab0f027";

//網(wǎng)易云信分配的密鑰,請?zhí)鎿Q你在管理后臺應(yīng)用下申請的appSecret

String appSecret = "xxxxxxxx";

//隨機(jī)數(shù)(最大長度128個字符)

String nonce = "12345";

TimeSpan ts = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1);

Int32 ticks = System.Convert.ToInt32(ts.TotalSeconds);

//當(dāng)前UTC時間戳,從1970年1月1日0點(diǎn)0 分0 秒開始到現(xiàn)在的秒數(shù)(String)

String curTime = ticks.ToString();

//SHA1(AppSecret + Nonce + CurTime),三個參數(shù)拼接的字符串,進(jìn)行SHA1哈希計算,轉(zhuǎn)化成16進(jìn)制字符(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";

//執(zhí)行Http請求

HttpClient.HttpPost(url, null, headers);

}

}

}

常見錯誤碼

所有的短信HTTP請求均有response,response有兩部分組成,

第一部分是code,代表code具體的內(nèi)容,成功還是失敗

第二部分是desc或者msg,代表錯誤原因描述(非code=200的情況,才會有desc)

414參數(shù)錯誤

1. checksum

{"desc":"checksum","code":414}

典型的checksum計算錯誤,需要自行核對計算checksum的參數(shù)算法,前提是保證這個appSecret是屬于您在管理后臺的應(yīng)用下的。

2. bad http header

{"desc":"bad http header","code":414}

典型的請求http header計算錯誤,需要自行核對請求header中的4個參數(shù),分別為Appkey,Nonce,Curtime,CheckSum。(上述文檔可以查詢這4個參數(shù))

3. 'mobiles' should be json format

{"code":414,"msg":"'mobiles' should be json format"}

典型的mobiles的參數(shù)傳的有問題,因為文檔的要求是jsonArray的格式,所以需要保證這個mobiles的參數(shù)是jsonArray的。例如:Java的格式為“['xxx','xxxx']”,其他代碼方式請自行參考解決。

4. 'params' should be json format

{"code":414,"msg":"'params' should be json format"}

典型的params的參數(shù)傳的有問題,因為文檔的要求是jsonArray的格式,所以需要保證這個params的參數(shù)是jsonArray的,并且要注意你的參數(shù)數(shù)量,例如:Java的格式為“['xxx','xxxx']”,其他代碼方式請自行參考解決。

5. sms template specify by id not found

{"code":414,"msg":"sms template specify by id not found"}

典型的短信模板與您的Appkey對應(yīng)不上,導(dǎo)致參數(shù)傳的有問題。需要保證當(dāng)前審核過的短信模板,與您的這個當(dāng)前應(yīng)用下的Appkey是一一對應(yīng)的,否則就會出現(xiàn)這樣的錯誤。

404對象不存在

1. template id not exist

{"code":404,"msg":"template id not exist"}

典型的短信模板與您發(fā)起的http請求的url不一致,首先要檢查管理后臺審核的模板是否與您的請求一致,比如通知類模板請求的url是sendTemplate.action,驗證碼模板請求的url是sendcode.action,這些在上述文檔中都有描述,可以查看。

400 HTTP錯誤

1. HTTP Status 400

這個錯誤是HTTP常見錯誤, 400 請求出錯 由于語法格式有誤,服務(wù)器無法理解此請求,一般出現(xiàn)的情況,都是短信請求的參數(shù)body與短信請求的URL不匹配導(dǎo)致的,只要參考檢查上述文檔中的URL,以及文檔中的body參數(shù)即可。

余額預(yù)警闕值

余額預(yù)警闕值,先可以登錄管理后臺,點(diǎn)擊左側(cè)“總覽”,當(dāng)前頁有個“”余額預(yù)警”,可以自行配置,余額提醒。

短信回執(zhí)抄送

現(xiàn)在云信支持短信的回執(zhí)抄送,抄送詳細(xì)解釋在Server端文檔,配置抄送地址在管理后臺中的當(dāng)前應(yīng)用下,有個“消息抄送配置”,配置地址可以是地址,也可以是域名。短信的抄送只要通道給了回執(zhí),原封不動的給抄送出去,包括發(fā)送成功和失敗(如黑名單,空號等等),如果通道那邊沒有給回執(zhí),那我們這邊就不會抄送。另外,如果短信被反垃圾了,也不會有抄送,這個相當(dāng)于,短信都沒投遞到通道服務(wù)商那邊。

本篇文檔內(nèi)容是否對您有幫助?

有幫助

我要吐槽

如果遇到產(chǎn)品相關(guān)問題,您可 提交工單 或 在線客服 尋求幫助。

您的改進(jìn)建議

×

問題類型

內(nèi)容錯誤

內(nèi)容沒更新

描述不清

鏈接有誤

步驟不完整

內(nèi)容缺失(缺少代碼/示例)

其他

更多建議

請輸入您的建議或問題(至少5個字符,至多500個字符)

聯(lián)系方式

標(biāo)記內(nèi)容

同時提交標(biāo)記內(nèi)容

提交

此文檔對你是否有幫助

×

有幫助

我要吐槽

×

反饋成功

非常感謝您的反饋,我們會繼續(xù)努力做得更好。

總結(jié)

以上是生活随笔為你收集整理的网易云信短信接口java_短信接入示例的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。