以下示例代码适用于 www.apishop.net 网站下的API,使用本文提及的接口调用代码示例前,您需要先申请相应的API服务。

  1. 短信服务:通知类和验证码短信,全国三网合一通道,5秒内到达,费用低至3.3分/条。可联系客服调整短信接收条数上限。
  2. 手机号归属地查询:根据中国大陆手机号获取归属地信息
  3. 电信基站查询:通过电信基站的系统识别码、网络识别码和基站号进行基站位置查询。
  4. 移动、联通基站查询:通过移动联通基站的小区号和基站号进行基站位置查询。
  5. IP地址查询:根据IP地址或者域名,查询该IP所属的区域
  6. 营销短信:适用于优惠折扣、促销、推广、购物券等活动,需在短信最后加"退订回T"

**API Shop(apishop.net)提供多达50款的常用第三方API,可以从github上下载代码示例合集:https://github.com/apishop/All-APIs**

以上接口均包含PHP、Python、C#和Java等四种语言的代码示例,以 营销短信 API为例:

(1)基于PHP的 营销短信 API服务请求的代码示例

<?php
$method = "POST";
$url = "https://api.apishop.net/communication/sms/sendMessage";
$headers = NULL;
$params = array(
    "phoneNum" => "", //目标手机号
    "templateID" => "", //短信模板ID
    "params" => "", //短信变量字段,用于替换短信模板中的@字符,长度最大20
);

$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("\ufeff", "", $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服务请求的代码示例

#!/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')

def apishop_send_request(method, url, params=None, headers=None):
    '''
    转发请求到目的主机
    @param method str 请求方法
    @param url str 请求地址
    @param params dict 请求参数
    @param headers dict 请求头
    '''
    method = str.upper(method)
    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/sendMessage"
headers = None
params = {
    "phoneNum":"", #目标手机号
    "templateID":"", #短信模板ID
    "params":"", #短信变量字段,用于替换短信模板中的@字符,长度最大20
}
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)基于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
    **/
    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/sendMessage";
            Dictionary<string, string> param = new Dictionary<string, string>();
            param.Add("phoneNum", ""); //目标手机号
    param.Add("templateID", ""); //短信模板ID
    param.Add("params", ""); //短信变量字段,用于替换短信模板中的@字符,长度最大20

            Dictionary<string, string> headers = null;
            string result = apishop_send_request(method, url, param, headers);
            if (result == "")
            {
                //返回内容异常,发送请求失败
                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();
        }
    }
}

(4)基于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;

/**
* httpUrlConnection访问远程接口工具
*/
public class Api
{
    /**
    * 方法体说明:向远程接口发起请求,返回字节流类型结果
    * param url 接口地址
    * param requestMethod 请求方式
    * param params 传递参数     重点:参数值需要用Base64进行转码
    * return InputStream 返回结果
    */
    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.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            // 设置连接超时时间
            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/sendMessage";
        String requestMethod = "POST";
        Map<String, String> params = new HashMap<String, String>();
        params.put("phoneNum", ""); //目标手机号
    params.put("templateID", ""); //短信模板ID
    params.put("params", ""); //短信变量字段,用于替换短信模板中的@字符,长度最大20
        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("发送请求失败");
        }
    }
}

通讯服务类API调用的代码示例合集:短信服务、手机号归属地查询、电信基站查询等的更多相关文章

  1. 出行服务类API调用的代码示例合集:长途汽车查询、车型大全、火车票查询等

    以下示例代码适用于 www.apishop.net 网站下的API,使用本文提及的接口调用代码示例前,您需要先申请相应的API服务. 长途汽车查询:全国主要城市的长途汽车时刻查询,汽车站查询 车型大全 ...

  2. 天气类API调用的代码示例合集:全国天气预报、实时空气质量数据查询、PM2.5空气质量指数等

    以下示例代码适用于 www.apishop.net 网站下的API,使用本文提及的接口调用代码示例前,您需要先申请相应的API服务. 全国天气预报:数据来自国家气象局,可根据地名.经纬度GPS.IP查 ...

  3. 位置信息类API调用的代码示例合集:中国省市区查询、经纬度地址转换、POI检索等

    以下示例代码适用于 www.apishop.net 网站下的API,使用本文提及的接口调用代码示例前,您需要先申请相应的API服务. 中国省市区查询:2017最新中国省市区地址 经纬度地址转换:经纬度 ...

  4. 生活常用类API调用的代码示例合集:邮编查询、今日热门新闻查询、区号查询等

    以下示例代码适用于 www.apishop.net 网站下的API,使用本文提及的接口调用代码示例前,您需要先申请相应的API服务. 邮编查询:通过邮编查询地名:通过地名查询邮编 今日热门新闻查询:提 ...

  5. 开发工具类API调用的代码示例合集:六位图片验证码生成、四位图片验证码生成、简单验证码识别等

    以下示例代码适用于 www.apishop.net 网站下的API,使用本文提及的接口调用代码示例前,您需要先申请相应的API服务. 六位图片验证码生成:包括纯数字.小写字母.大写字母.大小写混合.数 ...

  6. WCF服务开发与调用的完整示例

    WCF服务开发与调用的完整示例 开发工具:VS2008 开发语言:C# 开发内容:简单的权限管理系统 第一步.建立WCF服务库 点击确定,将建立一个WCF 服务库示例程序,自动生成一个包括IServi ...

  7. C++用LuaIntf调用Lua代码示例

    C++用LuaIntf调用Lua代码示例 (金庆的专栏 2016.12) void LuaTest::OnResponse(uint32_t uLuaRpcId, const std::string& ...

  8. .net core实践系列之短信服务-Api的SDK的实现与测试

    前言 上一篇<.net core实践系列之短信服务-Sikiro.SMS.Api服务的实现>讲解了API的设计与实现,本篇主要讲解编写接口的SDK编写还有API的测试. 或许有些人会认为, ...

  9. .net core实践系列之短信服务-Sikiro.SMS.Api服务的实现

    前言 上篇<.net core实践系列之短信服务-架构设计>介绍了我对短信服务的架构设计,同时针对场景解析了我的设计理念.本篇继续讲解Api服务的实现过程. 源码地址:https://gi ...

随机推荐

  1. JMeter之断言 - 响应文本

    1.  响应数据: 2.  添加响应断言: 3.设置响应断言,本例中 设置 响应文本 中 包括 success 字符串的 为真,即通过. 4.如果设置 响应文本 中 包括 error 字符串的 为真, ...

  2. Shader 入门笔记(二) CPU和GPU之间的通信

    渲染流水线的起点是CPU,即应用阶段. 1)把数据加载到显存中 2)设置渲染状态,通俗说这些状态定义了场景中的网格是怎样被渲染的. 3)调用DrawCall,一个命令,CPU通知GPU.(这个命令仅仅 ...

  3. 【转】Matlab中的括号()[] {}

    Matlab中经常会用到括号去引用某Array或者是cell的内容,但三者有什么具体区别呢?] []

  4. Java在已存在的pdf文件中生成文字和图片--基础

    自我总结,有什么不足之处请告知,感激不尽!下一次总结pdf模板映射生成报表(应对多变的pdf报表需求,数据提供和报表生成解耦). 目的:在给定的pdf模板上生成报表,就需要知道最基本的操作:文字添加, ...

  5. Oracle中 in、exists、not in,not exists的比较

    最基本的区别: in 对主表使用索引 exists 对子表使用索引 not in 不使用索引 not exists 对主子表都使用索引 写法: exist的where条件是: "...... ...

  6. c# Char && string

    char 支持的方法 字符串 声明字符串 String str = [null]; 可以用此方法声明一个空字符串   连接字符串 str +"" + str1; 比较两个字符串 C ...

  7. Dell服务器R320在Centos6.5系统上安装MegaCli管理主板集成磁盘阵列卡

    折腾了两天啊,我的神啊,,终于可以安装了 针对Dell服务器的R320版本主板集成的磁盘阵列卡,需要下载MegaCli 8或更新版本 下载链接: http://pan.baidu.com/s/1mgB ...

  8. Java字节码基础[转]

    原文链接:http://it.deepinmind.com/jvm/2014/05/24/mastering-java-bytecode.html Java是一门设计为运行于虚拟机之上的编程语言,因此 ...

  9. Laravel5.5核心架构理解

    1.依赖注入 方法传入组件名,框架会自动实例化,方法内可直接使用 例如最常用的requert对象 2.服务容器 其实,Laravel 的核心就是一个 IoC 容器,Laravel 的核心本身十分轻量, ...

  10. 开发板访问linux方法

    1.使用网线分别将 PC 机与开发板连接到交换机. 2.保证 windows能 ping通 Linux. 2.1.关闭 windows 系统中的其他网络连接,只保留用来和交换机连接的网卡. 2.2.网 ...