Skip to content

Commit 2394bbb

Browse files
committed
Add initial PostWithHeaders example
1 parent 5bda5b6 commit 2394bbb

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
/*
2+
POST with headers client for ArduinoHttpClient library
3+
Connects to server once every five seconds, sends a POST request
4+
with custome headers and a request body
5+
6+
note: WiFi SSID and password are stored in config.h file.
7+
If it is not present, add a new tab, call it "config.h"
8+
and add the following variables:
9+
char ssid[] = "ssid"; // your network SSID (name)
10+
char pass[] = "password"; // your network password
11+
12+
created 14 Feb 2016
13+
by Tom Igoe
14+
modified 18 Mar 2017
15+
by Sandeep Mistry
16+
17+
this example is in the public domain
18+
*/
19+
#include <ArduinoHttpClient.h>
20+
#include <WiFi101.h>
21+
#include "config.h"
22+
23+
char serverAddress[] = "192.168.0.3"; // server address
24+
int port = 8080;
25+
26+
WiFiClient wifi;
27+
HttpClient client = HttpClient(wifi, serverAddress, port);
28+
int status = WL_IDLE_STATUS;
29+
String response;
30+
int statusCode = 0;
31+
32+
void setup() {
33+
Serial.begin(9600);
34+
while ( status != WL_CONNECTED) {
35+
Serial.print("Attempting to connect to Network named: ");
36+
Serial.println(ssid); // print the network name (SSID);
37+
38+
// Connect to WPA/WPA2 network:
39+
status = WiFi.begin(ssid, pass);
40+
}
41+
42+
// print the SSID of the network you're attached to:
43+
Serial.print("SSID: ");
44+
Serial.println(WiFi.SSID());
45+
46+
// print your WiFi shield's IP address:
47+
IPAddress ip = WiFi.localIP();
48+
Serial.print("IP Address: ");
49+
Serial.println(ip);
50+
}
51+
52+
void loop() {
53+
Serial.println("making POST request");
54+
String postData = "name=Alice&age=12";
55+
56+
client.beginRequest();
57+
client.post("/");
58+
client.sendHeader("Content-Type", "application/x-www-form-urlencoded");
59+
client.sendHeader("Content-Length", postData.length());
60+
client.sendHeader("X-Custom-Header", "custom-header-value");
61+
client.endRequest();
62+
client.print(postData);
63+
64+
// read the status code and body of the response
65+
statusCode = client.responseStatusCode();
66+
response = client.responseBody();
67+
68+
Serial.print("Status code: ");
69+
Serial.println(statusCode);
70+
Serial.print("Response: ");
71+
Serial.println(response);
72+
73+
Serial.println("Wait five seconds");
74+
delay(5000);
75+
}

examples/PostWithHeaders/config.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
char ssid[] = "ssid"; // your network SSID (name)
2+
char pass[] = "password"; // your network password

0 commit comments

Comments
 (0)