简体   繁体   中英

How do I use method POST in Arduino IDE Ethernet Library, using Ruby on Rails API as post method?

friends.

I want to post data to web server from my Arduino setup, and I want to post it via Post Method to server side, running Ruby on Rails.

Already test my backend using postman, and it works like a charm.

Now I have a problem when I want to post it from arduino setup, it doesn't work. Server side never get the connection from arduino.

For Arduino setup I use ethernet.h Library.

    //------------------------------------------
// Park Sensor Prototype
// Only insert if there is car parked
//------------------------------------------
#include <Ethernet.h>
//servername
  char server[] = "https://spark-backend.herokuapp.com";

  byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
  EthernetClient client;
  String data;
  bool flagstatus = false;

void setup() { 
  Serial.begin(9600);

  // Connect to Ethernet
  Ethernet.begin(mac);
}

void loop() {

  int sensorvalue = analogRead(A0);  // LightValue, read from sensor pin A0
//  String templ= "sensorvalue=";
//  data = templ + String(sensorvalue);


  String parkspot_id= "{parkspot_id:""'""SP001""'"",";
  String sensor_in="sensor_in:""'""";
  String user_id=",user_id:""'""U001""'""}";
  String valueinput = String(sensorvalue);
  //data = parkspot_id + sensor_in + "'"valueinput"'"+","+user_id;
  data = parkspot_id +sensor_in+valueinput+"'"+user_id;

/*
{ park_spot_id: “SP001” , sensor_in: “100”, user_id:”U001”}
*/

  //there is a car parked
  if(sensorvalue >=1000){
    if(flagstatus == false){
    Serial.println("Insert to DB, there is a car just parked");
            if (client.connect(server, 80)){ 
              Serial.println("Connected to server");
              Serial.println(data);
              client.println("POST /api/v1/parks HTTP/1.1"); 
              client.print("Host: ");
              client.println(server); 
              client.println("Content-Type: application/x-www-form-urlencoded"); 
              client.print("Content-Length: "); 
              client.println(data.length()); 
              client.println(); 
              client.print(data); 
              client.stop();
            } 
    flagstatus = true;
    } else {
      Serial.println("There is still a car parked");
      }
    } else{
      Serial.println("There is no car parked");
      flagstatus = false;
      }
  delay(10000);  // delay ten seconds
}

I really need your advice :D Thank you in advance. Please correct me or teach me how to solve it :)

我认为您使用错误的标头Content-Type来发布JSON数据之类的数据:application / x-www-form-urlencoded,请将其更改为application / json。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM