Thursday, 30 June 2016

Use Arduino HttpClient post to send json


If you want to use arduino Httpclient to do http POST request, the good news is it support POST.

         unsigned int HttpClient::post(String &url, String &data)

However, the bad news is it doesn't support sending Json.

You can create a json string and send it, but you sever side will just get a string.

If you check the source code of this function you will find out this. it need a new parameter:

    -H "Content-Type: application/json"


This is the source code:

unsigned int HttpClient::post(const char *url, const char *data) {
  begin("curl");
  if (insecure) {
    addParameter("-k");
  }
  addParameter("--request");
  addParameter("POST");
  addParameter("--data");
  addParameter(data);
  addHeader();
  addParameter(url);
  return run();
}


The solution is, you should do POST request yourself:


  HttpClient client;
  String apiURL = "http://xxxxxxx";
  String json = "{\"aaa\":[{\"bbb\" : \"ccc\",\"ddd\" : 8,\"xxx\" :10}]}";
  client.begin("curl");
  String conKey = "-H";
  client.addParameter(conKey);
  String contype = "Content-Type: application/json";
  client.addParameter(contype);
  client.addParameter("--request");
  client.addParameter("POST");
  client.addParameter("--data");
  client.addParameter(json.c_str());
  client.addParameter(apiURL.c_str());
  client.run();












No comments:

Post a comment