编译并调用iot中云端api的pub c++版本
1.首先打开链接:https://next.api.aliyun.com/api/Iot/2018-01-20/Pub?params={}&sdkStyle=old&tab=DEBUG&lang=CPP
在这里调试pub接口,填入正确的ProductKey,TopicFullName,MessageContent,如果是企业实例,需要选择对应的地域和IotInstanceId。
2.在SDK示例中,找到原版的c++代码,拷贝出来保存。
截图中的代码保存为 pub.cc:
#include <cstdlib>
#include <iostream>
#include <alibabacloud/core/AlibabaCloud.h>
#include <alibabacloud/core/CommonRequest.h>
#include <alibabacloud/core/CommonClient.h>
#include <alibabacloud/core/CommonResponse.h>
using namespace std;
using namespace AlibabaCloud;
int main( int argc, char** argv )
{
AlibabaCloud::InitializeSdk();
AlibabaCloud::ClientConfiguration configuration( "cn-shanghai" );
// specify timeout when create client.
configuration.setConnectTimeout(1500);
configuration.setReadTimeout(4000);
AlibabaCloud::Credentials credential( "", "" );
/* use STS Token
credential.setSessionToken( "" );
*/
AlibabaCloud::CommonClient client( credential, configuration );
AlibabaCloud::CommonRequest request(AlibabaCloud::CommonRequest::RequestPattern::RpcPattern);
request.setHttpMethod(AlibabaCloud::HttpRequest::Method::Post);
request.setDomain("iot.cn-shanghai.aliyuncs.com");
request.setVersion("2018-01-20");
request.setQueryParameter("Action", "Pub");
request.setQueryParameter("TopicFullName", "/${productKey}/${deviceName}/user/get");
request.setQueryParameter("ProductKey", "${productKey}");
request.setQueryParameter("MessageContent", "dGhpcyBpcyBhIGV4YW1wbGU=");
auto response = client.commonResponse(request);
if (response.isSuccess()) {
printf("request success.\n");
printf("result: %s\n", response.result().payload().c_str());
} else {
printf("error: %s\n", response.error().errorMessage().c_str());
printf("request id: %s\n", response.error().requestId().c_str());
}
AlibabaCloud::ShutdownSdk();
return 0;
}
2.登录阿里云ecs服务器,我的调试环境为:Ubuntu 20.04.2 LTS (GNU/Linux 5.4.0-73-generic x86_64)。
参考github中文档中的步骤依次执行:https://github.com/aliyun/aliyun-openapi-cpp-sdk/blob/master/README-CN.md
依次执行命令:
apt-get update
sudo apt-get install libcurl4-openssl-dev libssl-dev uuid-dev libjsoncpp-dev
//如果没有安装git,需要执行 sudo apt-get install git
git clone https://github.com/aliyun/aliyun-openapi-cpp-sdk.git
cd aliyun-openapi-cpp-sdk
mkdir sdk_build
cd sdk_build
cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr -DBUILD_PRODUCT="iot"..
make
sudo make install
到此iot库已经编译成功,下面是编译过程中的截图。
接下来编译pub测试用例,把上面的保存的代码(本示例中代码参数需要自行填入,否则会运行失败),放到服务器某个地方。
执行命令:
g++ -o pub pub.cc --std=c++11 -lalibabacloud-sdk-core -l alibabacloud-sdk-iot
./pub
下面执行效果:
我有话说: