国际短信API接口 C++ 示例代码
//linux下的编译:g++ ./test.cpp -o ./test //linux下的执行:chmod +x test &&./test #include <arpa/inet.h> #include#include #include <netinet/in.h> #include #include #include #include #include <sys/types.h> #include <sys/socket.h> #include <sys/wait.h> #include #include #define SA struct sockaddr #define MAXLINE 4096 #define MAXSUB 2000 #define MAXPARAM 2048 #define LISTENQ 1024 extern int h_errno; int basefd; const char *hostname = "api.ihuyi.com"; const char *send_sms_uri = "/isms/Submit.json"; /** * 发http post请求 */ ssize_t http_post(const char *page, const char *poststr) { char sendline[MAXLINE + 1], recvline[MAXLINE + 1]; ssize_t n; snprintf(sendline, MAXSUB, "POST %s HTTP/1.1\r\n" "Host: %s\r\n" "Content-type: application/x-www-form-urlencoded\r\n" "Content-length: %zu\r\n\r\n" "%s", page, hostname, strlen(poststr), poststr); write(basefd, sendline, strlen(sendline)); while ((n = read(basefd, recvline, MAXLINE)) > 0) { recvline[n] = '\0'; printf("%s", recvline); } return n; } int socked_connect(const char *arg) { struct sockaddr_in their_addr = {0}; char buf[1024] = {0}; char rbuf[1024] = {0}; char pass[128] = {0}; struct hostent *host = NULL; int sockfd = socket(AF_INET, SOCK_STREAM, 0); if(sockfd<0) { printf ("create the sockfd is failed\n"); return -1; } if((host = gethostbyname(arg))==NULL) { printf("Gethostname error: %s\n", hstrerror(h_errno)); return -1; } memset(&their_addr, 0, sizeof(their_addr)); their_addr.sin_family = AF_INET; their_addr.sin_port = htons(80); their_addr.sin_addr = *((struct in_addr *)host->h_addr); if(connect(sockfd,(struct sockaddr *)&their_addr, sizeof(struct sockaddr)) < 0) { close(sockfd); return -1; } printf ("connect is success\n"); return sockfd; } int main(void) { struct sockaddr_in servaddr; char str[50]; #if 0 //建立socket连接 sockfd = socket(AF_INET, SOCK_STREAM, 0); bzero(&servaddr, sizeof(servaddr)); servaddr.sin_addr =*(hostname); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(80); inet_pton(AF_INET, str, &servaddr.sin_addr); connect(sockfd, (SA *) & servaddr, sizeof(servaddr)); #endif if((basefd= socked_connect(hostname))==-1) { printf("connect is failed\n"); return -1; } printf("basefd is =%d\n",basefd); const char *account = "xxxxxxxx"; //APIID(用户中心【文本短信】-【国际短信】-【产品总览】查看) const char *password = "xxxxxxxxx"; //1、APIKEY(用户中心【文本短信】-【国际短信】-【产品总览】查看)2、动态密码(生成动态密码方式请看该文档末尾的说明) const char *mobile = "1 978234523"; //接收手机号码, 只能提交一个号码。(格式为:国家号+空格+手机号) const char *content = "Your verification code is 1125"; //国际短信内容 const char *time = "1623643787"; //Unix时间戳(10位整型数字,当使用动态密码方式时为必填) char params[MAXPARAM + 1]; char *cp = params; snprintf(cp, MAXPARAM + 1, "account=%s&password=%s&mobile=%s&content=%s&time=%s&s=%s", account,password,mobile,content,time, "s"); http_post(send_sms_uri, cp); printf("send the message is success\n"); close(basefd); exit(0); }