一封传话聚合推送各语言demo代码示例
前言
查看一封传话的API文档的GET申请只需一行代码,在url上拼接head和body参数即可实现推送。这里针对body数据量较大的状况,给出各语言实现的demo代码。
Tips:以下代码中的trigger与API文档中的send等价,trigger在send根底上做了高级个性加强解决,能够参考:一封传话聚合推送高级个性API
任何使用者都能够随便抉择调用任何一个API,在API的应用形式上没有差别。
PHP语言
<?php
// 通道码/口令码
$channel_code = "4d2dac865118761a14d10d7d3afe7c35";
$head = "测试题目";
$body = "测试内容";
$postdata = json_encode(
array(
'head' => $head,
'body' => $body
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/json',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$api_url = 'https://www.phprm.com/services/push/trigger/'.$channel_code;
$result = file_get_contents($api_url, false, $context);
echo $result;
如果你更偏向于应用curl库, 齐全能够本人实现或者参考以下开源的三方库里的curl代码。
一些开源的三方库
-
如果心愿应用业余推送库, 能够参考此开源我的项目, 【一封传话】聚合推送SDK曾经提交到Github和Gitee,通过composer能够间接装置SDK:
- Github: https://github.com/guanguans/notify
- Gitee: https://gitee.com/guanguans/notify
-
提供博客零碎新注册用户、新评论揭示插件, 能够参考插件源码或者间接在本人的网站应用:
- WordPress插件: https://github.com/teakong/wordpress-tixing 或者 https://gitee.com/teakong/wordpress-tixing
- Typecho插件: https://gitee.com/teakong/wordpress-tixing 或者 https://gitee.com/teakong/TypechoTixing
- 其余博客或网站插件: https://github.com/teakong/liuyan-weixin 或者 https://gitee.com/teakong/liuyan-weixin
JAVA语言
倡议应用Guava自带限流工具类, 例如10秒告警一次避免大量申请耗费你本人的服务器,如果应用redis分布式限流更好,这里还用到了Hutool工具包下的http申请类。
Hutool官网阐明文档: https://hutool.cn/docs/#/
最新maven如下
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.11</version>
</dependency>
java告警工具类demo:
import com.alibaba.fastjson2.JSONObject;
import com.google.common.util.concurrent.RateLimiter;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
/**
* Java零碎告警工具类
*/
public class SystemAlarmUtil {
private final static RateLimiter rateLimiter = RateLimiter.create(1d);
private SystemAlarmUtil() {
super();
}
public static String sendAlarmMessage(String title, String message) {
try {
// count 每次耗费的令牌10个, 那么每10秒才会通过一次 timeout 超时期待的工夫, 期待超过1秒就回绝发送
if (!rateLimiter.tryAcquire(10, 1, TimeUnit.SECONDS)) {
return null;
}
// 创立json对象作为requestBody
JSONObject jsonObject = new JSONObject();
jsonObject.put("head", title);
jsonObject.put("body", message);
// 增加申请头信息
Map<String, String> heads = new HashMap<>();
// 应用json发送申请,上面的是必须的
heads.put("Content-Type", "application/json;charset=UTF-8");
HttpResponse response = HttpRequest.post("https://www.phprm.com/services/push/trigger/4d2dac865118761a14d10d7d3afe7c35")
.headerMap(heads, false).body(String.valueOf(jsonObject)).timeout(5 * 1000).execute();
System.out.println("告警推送后果: "+response.body());
return response.body();
}
catch (Exception exception) {
}
return null;
}
public static void main(String[] args) {
SystemAlarmUtil.sendAlarmMessage("系统故障告警", "故障模块: 订单模块\n订单ID=xxxx\n订单金额: 100元\n故障起因: xxxx");
}
}
因为java生态比拟丰盛,而且简直所有人都有本人实现POST申请的工具类,这么就不提供SDK了。
Python语言
Python语言环境应用demo:
#coding:utf-8
import requests
import json
# 通道码/口令码
channel_code = '4d2dac865118761a14d10d7d3afe7c35'
head = '测试题目'
body = '测试内容'
headers={
'Content-Type': 'application/json'
}
url='https://www.phprm.com/services/push/send/'+channel_code
data={'head':head,'body':body}
res=requests.post(headers=headers,url=url,data=json.dumps(data),timeout=10)
print(json.dumps(res))
Go语言
Golang语言环境应用demo:
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"unsafe"
)
func SendMessage() error {
channelCode := "4d2dac865118761a14d10d7d3afe7c35"
message1 := make(map[string]interface{})
message1["head"] = "测试题目"
message1["body"] = "测试内容"
bytesData, err := json.Marshal(message1)
if err != nil {
fmt.Println(err.Error() )
return nil
}
reader := bytes.NewReader(bytesData)
url := fmt.Sprintf("https://www.phprm.com/services/push/send/%s", channelCode)
request, err := http.NewRequest("POST", url, reader)
if err != nil {
fmt.Println(err.Error())
return nil
}
request.Header.Set("Content-Type", "application/json;charset=UTF-8")
client := http.Client{}
resp, err := client.Do(request)
if err != nil {
fmt.Println(err.Error())
return nil
}
respBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println(err.Error())
return nil
}
str := (*string)(unsafe.Pointer(&respBytes))
fmt.Println(*str)
return nil
}
func main() {
SendMessage()
}
C#语言
笔者暂未装置C#运行环境所以这里只提供GET申请,不过置信对C#相熟的同学编写POST application/json申请不是难事。
// Get申请
string url = "https://www.phprm.com/services/push/send/4d2dac865118761a14d10d7d3afe7c35?head="
+ HttpUtility.UrlEncode("测试题目")
+ "&body="
+ HttpUtility.UrlEncode("测试内容" + DateTime.Now);
var response = await httpClient.GetAsync(url);
string res = await response.Content.ReadAsStringAsync();
Console.WriteLine("推送状态:" + response.StatusCode);
Console.WriteLine(res);
其余语言
敬请期待
参考:
https://www.phprm.com/push/h5/
http://push.phprm.com/doc/#/p/demo
一封传话推送工具API文档
一行代码实现微信音讯推送
一封传话聚合推送高级个性API
发表回复