Arduinojson: How to post json form webClient?

Created on 1 Aug 2016  路  5Comments  路  Source: bblanchon/ArduinoJson

I found how to get json in example JsonHttpClient.
But how to post json to server?

question

All 5 comments

Simply replace the HTTP verb "GET" by "POST".

See: https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol

I tried but failed.

    client.println("POST /players.json HTTP/1.1");
    client.println("Host: 192.168.1.11:3000");
    client.println("Content-Type: application/json");
    client.println("Cache-Control: no-cache");
    client.println("Postman-Token: cf21a8da-facf-ee7e-17a8-b91708299d8f");
    client.println();
    client.println("{\"num\":2}");

I also tried json.printTo(client) but failed too..
I use postman everything is OK.This is the code generated from postman..

POST /players.json HTTP/1.1
Host: 192.168.1.11:3000
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: 2ef31aa8-3f51-5b3f-7603-a180085ebc8f

{"num":3}

I used mkr1000.Maybe this is why..
I will try Ethernet shield later.

Line endings are important for HTTP.
So this issue and #327 may be related.

Anyway, this doesn't look like an issue in ArduinoJson, so I'm closing this thread.

Hi @zixzixzix

I was able to make a POST request containig JSON with the following block of code

if (client.connect(host, 3000))
{    
    Serial.println("\nConnected to server");
    // Make a HTTP request    
    client.println("POST /accel HTTP/1.1");
    client.println("Host: 192.168.0.24");
    client.println("Content-Type: application/json");
    client.print("Content-Length: ");
    client.println(object.measureLength());
    client.println();
    object.printTo(client);    
}

I noticed that when you do something like this:

client.print("Content-Length: " + object.measureLength());

the request does not work

Hi @giobauermeister,

This operation:

"Content-Length: " + object.measureLength()`

is adding a char pointer to an integer, which is almost never what you want to do.
It's very likely to cause an Access Violation because the result is a pointer to a location that can be unavailable.

Here are two alternatives:

/* The C version */
char tmp[32];
sprintf(tmp, "Content-Length: %d", object.measureLength());

// The C++ version
String("Content-Length: ") + object.measureLength();

Of course, splitting into two lines, like you did, is correct and is probably the most efficient in term of speed, code size and memory consumption.

Thank you for this comment, I'm sure it will help other users 馃憤

Was this page helpful?
0 / 5 - 0 ratings