Wendell
Wendell

Reputation: 1

Arduino POST request using JSON

I am trying to get my Arduino (with an Ethernet shield) to send a POST request with a JSON body to my locally hosted server.

I am using the ArduinoJson (version 6) and Ethernet libraries.

I am attempting to send a POST request to a local endpoint (hosted on my laptop) /routes/test by using ArduinoJSON's JSON creation functionality. Using the library, I create a DynamicJsonDocument named doc and write attributes to it. I then use serializeJson to write the doc's data to the POST request.

My Problem: I make a POST request to an endpoint /routes/test but when I console.log the body, it appears as empty. It seems like I am not including any body in my post request

Using utils.inspect on the request object, I get this:

body: {}

Is this a syntax issue or is there something fundamentally wrong with my method? Any help would be greatly appreciated!!.

#include <ArduinoJson.h>
#include <Ethernet.h>
#include <SPI.h>

byte mac[]      = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };   
byte ip[]       = { 10, 0, 0, 177 };                        
byte server[]   = { x, x, x, x };  

EthernetClient client;

void setup() {

  //Initialize Ethernet and account for 1s delay
  Ethernet.begin(mac, ip);
  Serial.begin(9600);
  delay(1000);

  Serial.println("connecting...");

  if (client.connect(server, 5000)) {
    Serial.println("connected");
  } else {
    Serial.println("connection failed");
  }

  //Create JSON doc and write a "name" attribute
  const size_t capacity = JSON_OBJECT_SIZE(1);
  DynamicJsonDocument doc(capacity);
  doc["name"] = "some random name";


  //POST request
  Serial.println("Begin POST Request");

  client.println("POST /routes/test");
  client.println();
  client.println("Host:  x.x.x.x");
  client.println("User-Agent: Arduino/1.0");
  client.println("Content-Type: application/json;charset=UTF-8");
  client.println("Connection: close");
  client.print("Content-Length: ");
  client.println(measureJson(doc));

  //This works like client.println, but prints doc to client
  serializeJson(doc, client);

  //To let me know that request has been completed
  Serial.println("Sent Get Request");


Upvotes: 0

Views: 6198

Answers (1)

mgmussi
mgmussi

Reputation: 552

I had a similar problem and I solved it by formatting the string in one client.print. Notice that MY_PATH must be in a simple /path format and not in a http://196.10.10.0/path format since POST is always used in an HTTP context:

String command = "POST " + MY_PATH + " HTTP/1.1";
String postData = "{\"name\":\"AX1_02\",\"sector\":\"\",\"ip\":\"" +
                   Ethernet.localIP().toString() + "\",\"mac\":\"" + ESP_MAC + "\"}";

client.print(command + "\r\n" +
             "Connection: Close\r\n" +
             "Content-Type: application/json\r\n" +
             "Content-Length: " + postData.length() + "\r\n" +
             "\r\n" +
             postData + "\r\n");

Upvotes: 0

Related Questions