HTTP API

HTTP, ThingsOn IoT Platform tarafından API olarak desteklenen bir veri alma/verme protokolüdür. HTTP en yaygın kullanıma sahip protokol olmasının yanı sıra basit yapısıyla bazı IoT projelerinde kullanmaya oldukça uygundur.

ThingsOn JSON formatında anahtar-değer (key-value) içeriğini destekler. Anahtar her zaman bir string iken, değer ise string, boolean, double ya da long veri tipinde olabilir.

Farklı programlama dillerinde ThingsOn HTTP API üzerinden platforma telemetri verisinin nasıl gönderildiğini açıklayan örnekler aşağıdadır;

Başlamadan Önce

[API_KEY]: Kod örneklerindeki [API_KEY] ifadesini platformda oluşturacağınız cihazın access token’i ile değiştirmeyi unutmayın! (köşeli parantezler dahil)

{“temperature”:100, “humidity”:40}: Aşağıdaki her bir örnek platforma Key-Value formatında bu veriyi gönderir. Bu veri gerçek dünyada göndermek istediğiniz telemetri verisi ile değiştirilmelidir.

HTTP

POST /api/v1/[API KEY]/telemetry HTTP/1.1 Host: cloud.thingson.io cache-control: no-cache {"temperature":100, "humidity":40}------WebKitFormBoundary7MA4YWxkTrZu0gW--

C (LibCurl)

CURL *hnd = curl_easy_init(); curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "POST"); curl_easy_setopt(hnd, CURLOPT_URL, "https://cloud.thingson.io/api/v1/[API KEY]/telemetry"); struct curl_slist *headers = NULL; headers = curl_slist_append(headers, "cache-control: no-cache"); curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, "{\"temperature\":100, \"humidity\":40}"); CURLcode ret = curl_easy_perform(hnd);

cURL

curl -X POST \ 'https://cloud.thingson.io/api/v1/[API%20KEY]/telemetry' \ -H 'cache-control: no-cache' \ -d '{"temperature":100, "humidity":40}'

C# (RestSharp)

var client = new RestClient("https://cloud.thingson.io/api/v1/[API%20KEY]/telemetry"); var request = new RestRequest(Method.POST); request.AddHeader("cache-control", "no-cache"); request.AddParameter("undefined", "{\"temperature\":100, \"humidity\":40}", ParameterType.RequestBody); IRestResponse response = client.Execute(request);

GO

package main import ( "fmt" "strings" "net/http" "io/ioutil" ) func main() { url := "https://cloud.thingson.io/api/v1/[API%20KEY]/telemetry" payload := strings.NewReader("{\"temperature\":100, \"humidity\":40}") req, _ := http.NewRequest("POST", url, payload) req.Header.Add("cache-control", "no-cache") res, _ := http.DefaultClient.Do(req) defer res.Body.Close() body, _ := ioutil.ReadAll(res.Body) fmt.Println(res) fmt.Println(string(body)) }

Java (OkHTTP)

OkHttpClient client = new OkHttpClient(); MediaType mediaType = MediaType.parse("application/octet-stream"); RequestBody body = RequestBody.create(mediaType, "{\"temperature\":100, \"humidity\":40}"); Request request = new Request.Builder() .url("https://cloud.thingson.io/api/v1/[API_KEY]/telemetry") .post(body) .addHeader("cache-control", "no-cache") .build(); Response response = client.newCall(request).execute();

JavaScript (XHR)

var data = "{\"temperature\":100, \"humidity\":40}"; var xhr = new XMLHttpRequest(); xhr.withCredentials = true; xhr.addEventListener("readystatechange", function () { if (this.readyState === 4) { console.log(this.responseText); } }); xhr.open("POST", "https://cloud.thingson.io/api/v1/[API_KEY]/telemetry"); xhr.setRequestHeader("cache-control", "no-cache"); xhr.send(data);

JavaScript (Jquery AJAX)

var settings = { "async": true, "crossDomain": true, "url": "https://cloud.thingson.io/api/v1/[API_KEY]/telemetry", "method": "POST", "headers": { "cache-control": "no-cache" }, "data": "{\"temperature\":100, \"humidity\":40}" } $.ajax(settings).done(function (response) { console.log(response); });

NodeJS

var http = require("https"); var options = { "method": "POST", "hostname": [ "cloud", "thingson", "io" ], "path": [ "api", "v1", "[API_KEY]", "telemetry" ], "headers": { "cache-control": "no-cache" } }; var req = http.request(options, function (res) { var chunks = []; res.on("data", function (chunk) { chunks.push(chunk); }); res.on("end", function () { var body = Buffer.concat(chunks); console.log(body.toString()); }); }); req.write("{\"temperature\":100, \"humidity\":40}"); req.end();

Objective-C (NSURL)

#import <Foundation/Foundation.h> NSDictionary *headers = @{ @"cache-control": @"no-cache" }; NSData *postData = [[NSData alloc] initWithData:[@"{"temperature":100, "humidity":40}" dataUsingEncoding:NSUTF8StringEncoding]]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://cloud.thingson.io/api/v1/[API_KEY]/telemetry"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0]; [request setHTTPMethod:@"POST"]; [request setAllHTTPHeaderFields:headers]; [request setHTTPBody:postData]; NSURLSession *session = [NSURLSession sharedSession]; NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if (error) { NSLog(@"%@", error); } else { NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; NSLog(@"%@", httpResponse); } }]; [dataTask resume];

PHP

<?php $request = new HttpRequest(); $request->setUrl('https://cloud.thingson.io/api/v1/[API_KEY]/telemetry'); $request->setMethod(HTTP_METH_POST); $request->setHeaders(array( 'cache-control' => 'no-cache' )); $request->setBody('{"temperature":100, "humidity":40}'); try { $response = $request->send(); echo $response->getBody(); } catch (HttpException $ex) { echo $ex; }

Python (http.client)

import http.client conn = http.client.HTTPConnection("cloud,thingson,io") payload = "{\"temperature\":100, \"humidity\":40}" headers = { 'cache-control': "no-cache" } conn.request("POST", "api,v1,[API_KEY],telemetry", payload, headers) res = conn.getresponse() data = res.read() print(data.decode("utf-8"))

Python (Requests)

import requests url = "https://cloud.thingson.io/api/v1/[API_KEY]/telemetry" payload = "{\"temperature\":100, \"humidity\":40}" headers = {'cache-control': 'no-cache'} response = requests.request("POST", url, data=payload, headers=headers) print(response.text)

Ruby (NET::HTTP)

require 'uri' require 'net/http' url = URI("https://cloud.thingson.io/api/v1/[API_KEY]/telemetry") http = Net::HTTP.new(url.host, url.port) request = Net::HTTP::Post.new(url) request["cache-control"] = 'no-cache' request.body = "{\"temperature\":100, \"humidity\":40}" response = http.request(request) puts response.read_body

Shell (wget)

wget --quiet \ --method POST \ --header 'cache-control: no-cache' \ --body-data '{"temperature":100, "humidity":40}' \ --output-document \ - 'https://cloud.thingson.io/api/v1/[API_KEY]/telemetry'

Swift (NSURL)

import Foundation let headers = ["cache-control": "no-cache"] let postData = NSData(data: "{"temperature":100, "humidity":40}".data(using: String.Encoding.utf8)!) let request = NSMutableURLRequest(url: NSURL(string: "https://cloud.thingson.io/api/v1/[API_KEY]/telemetry")! as URL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0) request.httpMethod = "POST" request.allHTTPHeaderFields = headers request.httpBody = postData as Data let session = URLSession.shared let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in if (error != nil) { print(error) } else { let httpResponse = response as? HTTPURLResponse print(httpResponse) } }) dataTask.resume()

Was this article helpful?
Dislike 0
Next:
Scroll to Top
ThingsOn Iot Platform

ThingsOn Canlı Demo Formu

Platformu 14 gün boyunca ücretsiz kullanmak için lütfen aşağıdaki formu doldurup “Gönder” butonuna tıklayın.