eoLinker-API_Shop_短信服务接口-调用示例代码,支持PHP、Python、Java等语言

eoLinker-API Shop 短信服务 调用示例代码

短信服务

通知类和验证码短信,全国三网合一通道,5秒内到达,费用低至3.3分/条。可联系客服调整短信接收条数上限。

该产品拥有以下APIs:
  1. 发送短信(验证码、通知类)

注意,该示例代码仅适用于 www.apishop.net 网站下API 使用该产品前,您需要通过 https://www.apishop.net/#/api/detail/?productID=62 申请API服务


1.基于PHP的 短信服务 API服务请求的代码示例
<?php
$method = "POST";
$url = "https://api.apishop.net/communication/sms/send";
$headers = NULL;
$params = array(			
		"phoneNum"=>"" //目标手机号(运营商限制同一手机号一天发送不得超过10条,特殊需求请与我们联系)			
		"templateID"=>"" //短信模板ID,短信模版审核通过后即生效			
		"params"=>"" //短信变量字段json数组,用于替换短信模板中的@字符,长度最大20,如短信模板里有2个变量,分别用123和abc替换,那么该参数的示例为[123,"abc"]		
);

$result = apishop_curl($method, $url, $headers, $params);
If ($result) {
   $body = json_decode($result["body"], TRUE);
   $status_code = $body["statusCode"];
   If ($status_code == "000000") {
       //状态码为000000, 说明请求成功
       echo "请求成功:" . $result["body"];
   } else {
       //状态码非000000, 说明请求失败
       echo "请求失败:" . $result["body"];
   }
} else {
   //返回内容异常,发送请求失败,以下可根据业务逻辑自行修改
   echo "发送请求失败";
}

/**
  * 转发请求到目的主机
  * @param $method string 请求方法
  * @param $URL string 请求地址
  * @param null $headers 请求头
  * @param null $param 请求参数
  * @return array|bool
  */
function apishop_curl(&$method, &$URL, &$headers = NULL, &$param = NULL)
{
   // 初始化请求
   $require = curl_init($URL);
   // 判断是否HTTPS
   $isHttps = substr($URL, 0, 8) == "https://" ? TRUE : FALSE;
   // 设置请求方式
   switch ($method) {
       case "GET":
           curl_setopt($require, CURLOPT_CUSTOMREQUEST, "GET");
           break;
       case "POST":
           curl_setopt($require, CURLOPT_CUSTOMREQUEST, "POST");
           break;
       default:
           return FALSE;
   }
   if ($param) {
       curl_setopt($require, CURLOPT_POSTFIELDS, $param);
   }
   if ($isHttps) {
       // 跳过证书检查
       curl_setopt($require, CURLOPT_SSL_VERIFYPEER, FALSE);
       // 检查证书中是否设置域名
       curl_setopt($require, CURLOPT_SSL_VERIFYHOST, 2);
   }
   if ($headers) {
   // 设置请求头
   curl_setopt($require, CURLOPT_HTTPHEADER, $headers);
   }
   // 返回结果不直接输出
   curl_setopt($require, CURLOPT_RETURNTRANSFER, TRUE);
   // 重定向
   curl_setopt($require, CURLOPT_FOLLOWLOCATION, TRUE);
   // 把返回头包含再输出中
   curl_setopt($require, CURLOPT_HEADER, TRUE);
   // 发送请求
   $response = curl_exec($require);
   // 获取头部长度
   $headerSize = curl_getinfo($require, CURLINFO_HEADER_SIZE);
   // 关闭请求
   curl_close($require);
   if ($response) {
       // 返回头部字符串
       $header = substr($response, 0, $headerSize);
       // 返回体
       $body = substr($response, $headerSize);
       // 过滤隐藏非法字符
       $bodyTemp = json_encode(array(
            0 => $body
       ));
       $bodyTemp = str_replace("", "", $bodyTemp);
       $bodyTemp = json_decode($bodyTemp, TRUE);
       $body = trim($bodyTemp[0]);
       // 将返回结果头部转成数组
       $respondHeaders = array();
       $header_rows = array_filter(explode(PHP_EOL, $header), "trim");
       foreach ($header_rows as $row) {
           $keylen = strpos($row, ":");
           if ($keylen) {
               $respondHeaders[] = array(
                   "key" => substr($row, 0, $keylen),
                   "value" => trim(substr($row, $keylen + 1))
               );
           }
       }
       return array(
           "headers" => $respondHeaders,
           "body" => $body
       );
   } else {
       return FALSE;
   }
}
2.基于Python的 短信服务 API服务请求的代码示例
//post请求
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 测试环境: python2.7
# 安装requests依赖 => pip install requests/ easy_install requests

# 导入requests依赖
import requests
import json
import sys

reload(sys)
sys.setdefaultencoding("utf-8")
   '''
   转发请求到目的主机
   @param method str 请求方法
   @param url str 请求地址
   @param params dict 请求参数
   @param headers dict 请求头
   '''
   if method == "POST":
       return requests.post(url=url, data=params, headers=headers)
   elif method == "GET":
       return requests.get(url=url, params=params, headers=headers)
   else:
       return None

method = "POST"
url = "https://api.apishop.net/communication/sms/send
headers = None
params = {
   apiKey : "参数1",
   phoneNum : "参数2",
   templateID : "参数3",
   params : "参数4"
}
result = apishop_send_request(method=method, url=url, params=params, headers=headers)
if result:
   body = result.text
   response = json.loads(body)
   status_code = response["statusCode"]
   if (status_code == "000000"):
       # 状态码为000000, 说明请求成功
       print("请求成功:%s" % (body,))
   else:
       # 状态码非000000, 说明请求失败
       print("请求失败: %s" % (body,))
   else:
       # 返回内容异常,发送请求失败
       print("发送请求失败"")
3.基于Java的 短信服务 API服务请求的代码示例
package net.apishop.www.controller;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.fastjson.JSONObject;

public class Api
{
   public static InputStream httpRequestToStream(String url, String requestMethod, Map<String, String> params)
   {
       InputStream is = null;
           try
           {
               String parameters = "";
               boolean hasParams = false;
               // 将参数集合拼接成特定格式,如name=zhangsan&age=24
               for (String key : params.keySet())
               {
                   String value = URLEncoder.encode(params.get(key), "UTF-8");
                   parameters += key + "=" + value + "&";
                   hasParams = true;
                   if (hasParams)
                   }
                {
                    parameters = parameters.substring(0, parameters.length() - 1);
                }
                // 请求方式是否为get
                boolean isGet = "get".equalsIgnoreCase(requestMethod);
                // 请求方式是否为post
                boolean isPost = "post".equalsIgnoreCase(requestMethod);
                if (isGet)
                {
                    url += "?" + parameters;
                }
                URL u = new URL(url);
                HttpURLConnection conn = (HttpURLConnection) u.openConnection();
                // 请求的参数类型(使用restlet框架时,为了兼容框架,必须设置Content-Type为“”空)
                conn.setRequestProperty("Content-Type", "application/octet-stream");
                // 设置连接超时时间
                conn.setConnectTimeout(50000);
                // 设置读取返回内容超时时间
                conn.setReadTimeout(50000);
                // 设置向HttpURLConnection对象中输出,因为post方式将请求参数放在http正文内,因此需要设置为ture,默认false
                if (isPost)
                {
                    conn.setDoOutput(true);
                }
                // 设置从HttpURLConnection对象读入,默认为true
                conn.setDoInput(true);
                // 设置是否使用缓存,post方式不能使用缓存
                if (isPost)
                {
                    conn.setUseCaches(false);
                }
                // 设置请求方式,默认为GET
                conn.setRequestMethod(requestMethod);
                // post方式需要将传递的参数输出到conn对象中
                if (isPost)
                {
                    DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
                    dos.writeBytes(parameters);
                    dos.flush();
                    dos.close();
                }
                // 从HttpURLConnection对象中读取响应的消息
                // 执行该语句时才正式发起请求
                is = conn.getInputStream();
            }
            catch(UnsupportedEncodingException e)
            {
                e.printStackTrace();
            }
            catch(MalformedURLException e)
            {
                e.printStackTrace();
            }
            catch(IOException e)
            {
                e.printStackTrace();
            }
            return is;
        }

        public static void main(String args[])
        {
            String url = "https://api.apishop.net/communication/sms/send";
            String requestMethod = "POST";
            Map<String, String> params = new HashMap<String, String>();
            params.put("apiKey", "参数1");
            params.put("phoneNum", "参数2");
            params.put("templateID", "参数3");
            params.put("params", "参数4");
            String result = null;
            try
            {
                InputStream is = httpRequestToStream(url, requestMethod, params);
                byte[] b = new byte[is.available()];
                is.read(b);
                result = new String(b);
            }
            catch(IOException e)
            {
                e.printStackTrace();
            }
            if (result != null)
            {
                JSONObject jsonObject = JSONObject.parseObject(result);
                String status_code = jsonObject.getString("statusCode");
                if (status_code == "000000")
                {
                    // 状态码为000000, 说明请求成功
                    System.out.println("请求成功:" + jsonObject.getString("result"));
                }
                else
                {
                    // 状态码非000000, 说明请求失败
                    System.out.println("请求失败:" + jsonObject.getString("desc"));
                }
            }
            else
            {
                // 返回内容异常,发送请求失败,以下可根据业务逻辑自行修改
                System.out.println("发送请求失败");
            }
        }
    }
}
4.基于C#的 短信服务 API服务请求的代码示例
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Web.Script.Serialization;

namespace apishop_sdk
{
   class Program
   {
       /**
        * 转发请求到目的主机
        * @param method string 请求方法
        * @param url string 请求地址
        * @param params Dictionary<string,string> 请求参数
        * @param headers Dictionary<string,string> 请求头
        * @return string
        * @return string
        **/
       static string apishop_send_request(string method, string url, Dictionary<string, string> param, Dictionary<string, string> headers)
       {
           string result = string.Empty;
           try
           {
               string paramData = "";
               if (param != null && param.Count > 0)
               {
                   StringBuilder sbuilder = new StringBuilder();
                   foreach (var item in param)
                   {
                       if (sbuilder.Length > 0)
                        {
                             sbuilder.Append("&");
                        }
                        sbuilder.Append(item.Key + "=" + item.Value);
                    }
                    paramData = sbuilder.ToString();
                }
                method = method.ToUpper();
                if (method == "GET")
                {
                    url = string.Format("{0}?{1}", url, paramData);
                }
                HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(url);
                if (method == "GET")
                {
                    wbRequest.Method = "GET";
                }
                else if (method == "POST")
                {
                    wbRequest.Method = "POST";
                    wbRequest.ContentType = "application/x-www-form-urlencoded";
                    wbRequest.ContentLength = Encoding.UTF8.GetByteCount(paramData);
                    using (Stream requestStream = wbRequest.GetRequestStream())
                    {
                        using (StreamWriter swrite = new StreamWriter(requestStream))
                        {
                            swrite.Write(paramData);
                        }
                    }
                }
                
                HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse();
                using (Stream responseStream = wbResponse.GetResponseStream())
                {
                    using (StreamReader sread = new StreamReader(responseStream))
                    {
                        result = sread.ReadToEnd();
                    }
                }
            }
            catch
            {
                return "";
            }
            return result;
        }
        
        class Response
        {
            public string statusCode;
        }
        static void Main(string[] args)
        {
            string method = "POST";
            string url = "https://api.apishop.net/communication/sms/send";
            Dictionary<string, string> param = new Dictionary<string, string>();
               param.Add("apiKey", "参数1");
               param.Add("phoneNum", "参数2");
               param.Add("templateID", "参数3");
               param.Add("params", "参数4");
            Dictionary<string, string> headers = null;
            string result = apishop_send_request(method, url, param, headers);
            string result = apishop_send_request(method, url, param, headers);
            {
                //返回内容异常,发送请求失败
                Console.WriteLine("发送请求失败");
                return;
            }
            
            Response res = new JavaScriptSerializer().Deserialize<Response>(result);
            if (res.statusCode == "000000")
            {
                //状态码为000000, 说明请求成功
                Console.WriteLine(string.Format("请求成功: {0}", result));
            }
            else
            {
                //状态码非000000, 说明请求失败
                 Console.WriteLine(string.Format("请求失败: {0}", result));
            }
            Console.ReadLine();
        }
    }
}

转载于:https://my.oschina.net/u/3784238/blog/1623485

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值