douzhuo3233 2019-05-29 07:25
浏览 797

可以arduino发送重复的http请求,并从响应中获取和解析数据

I want to use an Arduino for a project. What i want is arduino should send repeated http request (say every minute) with some data (most probably the IP address) to the server. And server will return a response with some data in JSON format and arduino should parse the data and write it to a text file. The data is some configuration parameters from the database. Can I do it with Arduino? I saw some posts saying that the repeated http request is not possible? any kind of help? A sample code will be really helpful. I am using Arduino mega with Ethernet shield.

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

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 0, 177);
IPAddress myDns(192, 168, 0, 1);

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;
void setup(){
// Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
 // start the Ethernet connection:
  Serial.println("Initialize Ethernet with DHCP:");
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
  // Check for Ethernet hardware present
    if (Ethernet.hardwareStatus() == EthernetNoHardware) {
      Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
      while (true) {
        delay(1); // do nothing, no point running without Ethernet hardware
      }
    }
    if (Ethernet.linkStatus() == LinkOFF) {
      Serial.println("Ethernet cable is not connected.");
    }
// try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip, myDns);
  } else {
    Serial.print("  DHCP assigned IP ");
    Serial.println(Ethernet.localIP());
  }

// give the Ethernet shield a second to initialize:
  delay(1000);
  Serial.print("connecting... ");
}


void loop(){

  if (Ethernet.begin(mac) !=0){
    HttpClient http; 
    http.begin("http://jsonplaceholder.typicode.com/comments?id=10"); //Specify the URL
    int httpCode = http.GET();                                        //Make the request
    if (httpCode > 0) { //Check for the returning code
        String payload = http.getString();
        Serial.println(httpCode);
        Serial.println(payload);
      } 
    else {
      Serial.println("Error on HTTP request");
    }
    http.end(); //Free the resources
  }
  delay(10000);  

    }

I tried the above code to send an http request. But getting an error no matching function for call to 'HttpClient::HttpClient()'

any suggestions would be really helpful.

  • 写回答

1条回答 默认 最新

  • dongwang6837 2019-05-29 16:18
    关注

    You don't have any limitation for sending repeated requests except the timing for each request. Your code is fine except the part that making an HTTP request. The default Arduino library is a little complicated for handling HTTP requests (e.g there is no HttpClient.GET).

    There are many high-level API out there that handles the requests for you and also can set various header types.

    For example ArduinoHTTPClient is a good one. Just grab the library and check out examples. I rewrite your code based on that and you will get your JSON response body. Then you can simply use one of the JSON parsers like ArduinoJSON to parse results.

    #include <ArduinoHttpClient.h>
    #include <SPI.h>
    #include <Ethernet.h>
    
    // Enter a MAC address for your controller below.
    // Newer Ethernet shields have a MAC address printed on a sticker on the shield
    byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
    
    // Set the static IP address to use if the DHCP fails to assign
    IPAddress ip(192, 168, 0, 177);
    IPAddress myDns(192, 168, 0, 1);
    
    char serverAddress[] = "http://jsonplaceholder.typicode.com"; // server address
    int port = 80;
    
    EthernetClient EthClient;
    HttpClient client = HttpClient(EthClient, serverAddress, port);
    
    void setup()
    {
        Serial.begin(9600);
    
        // start the Ethernet connection:
        Serial.println("Initialize Ethernet with DHCP:");
        if (Ethernet.begin(mac) == 0)
        {
            Serial.println("Failed to configure Ethernet using DHCP");
            // Check for Ethernet hardware present
            if (Ethernet.hardwareStatus() == EthernetNoHardware)
            {
                Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
                while (true)
                {
                    delay(1); // do nothing, no point running without Ethernet hardware
                }
            }
            if (Ethernet.linkStatus() == LinkOFF)
            {
                Serial.println("Ethernet cable is not connected.");
            }
            // try to congifure using IP address instead of DHCP:
            Ethernet.begin(mac, ip, myDns);
        }
        else
        {
            Serial.print("  DHCP assigned IP ");
            Serial.println(Ethernet.localIP());
        }
    }
    void loop()
    {
        Serial.println("making GET request");
        client.get("/comments?id=10");
    
        // read the status code and body of the response
        int statusCode = client.responseStatusCode();
        String response = client.responseBody();
    
        Serial.print("Status code: ");
        Serial.println(statusCode);
        Serial.print("Response: ");
        Serial.println(response);
        Serial.println("Wait five seconds");
        delay(5000);
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3