Skip to content

Commit b395104

Browse files
added a sample REST API HTTP Request POST with encoded JSON Data
1 parent ad71737 commit b395104

File tree

1 file changed

+96
-0
lines changed

1 file changed

+96
-0
lines changed

REST-API-POST/REST-API-POST.ino

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
#include <SPI.h>
2+
#include <Ethernet.h>
3+
#include <ArduinoJson.h>
4+
5+
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
6+
IPAddress my_ip(192,168,1,75);
7+
IPAddress server(192,168,1,201);
8+
9+
EthernetClient client;
10+
11+
String params;
12+
StaticJsonBuffer<200> jsonBuffer;
13+
14+
void setup() {
15+
int monitor_serial = 9600;
16+
Serial.begin(monitor_serial);
17+
18+
// wait for serial port to connect
19+
while(!Serial) {
20+
21+
}
22+
23+
Ethernet.begin(mac, my_ip);
24+
25+
params = "value1=";
26+
params.concat(5);
27+
params.concat("&value=");
28+
params.concat(10);
29+
30+
// parse String to JSON Object
31+
JsonObject& root = jsonBuffer.createObject();
32+
root["value"] = 5;
33+
root["value2"] = 10;
34+
35+
// this is example for creating nested array data
36+
// JsonArray& data = root.createNestedArray("data");
37+
// data.add(123);
38+
// data.add(321);
39+
40+
// this is for printing json encoded to serial
41+
// root.printTo(Serial);
42+
43+
Serial.print("My IP Address : ");
44+
Serial.println(my_ip);
45+
Serial.print("Destination Server : ");
46+
Serial.println(server);
47+
Serial.println("Connecting ...");
48+
delay(3000);
49+
50+
// connect to server with standard port 80
51+
if(client.connect(server,80)) {
52+
Serial.println("Connected.");
53+
Serial.println();
54+
delay(1000);
55+
56+
Serial.println("Sending Data ...");
57+
58+
// write http request
59+
client.println("POST /epass-passenger/api/post HTTP/1.1");
60+
Serial.println("POST /epass-passenger/api/post HTTP/1.1");
61+
client.print("Host : ");
62+
client.println(server);
63+
client.println("Content Type : application/x-www-form-urlencoded");
64+
client.println("Connection : close");
65+
client.println("User-Agent : Arduino/1.0");
66+
client.print("Content-Length : ");
67+
client.println(root.measureLength());
68+
client.println();
69+
Serial.print("Sent Data : ");
70+
root.printTo(client);
71+
root.printTo(Serial);
72+
client.println();
73+
Serial.println();
74+
} else {
75+
Serial.print("Cannot connect to ");
76+
Serial.println(server);
77+
}
78+
}
79+
80+
void loop() {
81+
if(client.available()) {
82+
char c = client.read();
83+
Serial.print(c);
84+
}
85+
86+
if(!client.connected()) {
87+
Serial.println();
88+
Serial.println("Disconnecting ...");
89+
delay(3000);
90+
client.stop();
91+
Serial.println("Disconnected.");
92+
while(true) {
93+
delay(1);
94+
}
95+
}
96+
}

0 commit comments

Comments
 (0)