HttpPost with form data in Particle IDE

I am trying to send a form data along with a httppost and am not sure what I need to do next, or how to send it. I am using the HttpClient.h library for arduino to complete the post and looking at requestbin shows that the raw body is being sent.
Here is the code that I am using:

include "HttpClient.h"

int button = D2;
int led1 = D7;
int led2 = D5;
int buttonState;
char randomValue[16];
String serialNumber;
String ip;
String info;
HttpClient http;

http_header_t headers[] = {
  {"Content-Type", "application/x-www-urlencoded"},
  {"Accept", "application/*"},
  {"Accept", "/"},
  {NULL, NULL}
};

http_request_t request;
http_response_t response;

static const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abvdefghijklmnopqrstuvwxyz";

int stringLength = sizeof(alphanum) - 1;

void setup()
{
    pinMode(button, INPUT);
    pinMode(led1, OUTPUT);
    pinMode(led2, OUTPUT);
    request.hostname = "requestb.in";
    request.port = 80;
    request.path = "/1b7oqcn1";
}

void loop()
{
  serialNumber = System.deviceID();
  buttonState = digitalRead(button);

  uint32_t seed = HAL_RNG_GetRandomNumber();
  srand(seed);
  for (int z = 0; z < 16; z++)
  {
    randomValue[z] = genRandom();
  }

  if (buttonState == LOW)
  {
    blinkLed(led1);
  }
  else
  {
    Particle.subscribe("spark/", handler);
    Particle.publish("spark/device/ip");
    blinkLed(led2);
    blinkLed(led2);
  }
}

void handler(const char *topic, const char *data)
{
  ip = data;
  info = String::format("serialNumber: %s, randomValue: %s, ip: %s", serialNumber.c_str(), randomValue, ip.c_str());
  request.body = info;
  http.post(request, response, headers);
}

char genRandom()
{
  return alphanum[rand() % stringLength];
}

void blinkLed(int led)
{
  digitalWrite(led, HIGH);
  delay(500);
  digitalWrite(led, LOW);
  delay(500);
}

Just a side note:
Particle.subscribe() should only be set up once. After that the subscription stands till you Particle.unsubscribe() all standing subscriptions.

Try adding \r\n at the end of your request body.

But what exactly is your issue?

I’m not sure how to make use form with a post in the ide, unlike the webhooks in which it is provided for you, and I need to send serialNumber, randomValue and ip in set fields.

Then you might find some hints in this thread
HttpClient post to influxdb problem

1 Like

I’m trying to get it do post the three variables serialNumber, randomValue and ip as a form post but at the moment requestbin is only showing them coming up as a raw body and I was wondering how to change my code that I can do it.