How to get the url from the GET Request with Arduino Uno

Hey everyone,

I'm trying to create an Application which get 3 params via the URL in the GET Request. With the client.read() function I can see the URL with the params on the Serial Monitor, but I don't know how to access only the url.
In the Serial Monitor I see this: GET /H?from=value1&to=value2&lastOne=false HTTP/1.1

/*
  WiFi Web Server LED Blink

 A simple web server that lets you blink an LED via the web.
 This sketch will print the IP address of your WiFi module (once connected)
 to the Serial Monitor. From there, you can open that address in a web browser
 to turn on and off the LED on pin 9.

 If the IP address of your board is yourAddress:
 http://yourAddress/H turns the LED on
 http://yourAddress/L turns it off

 This example is written for a network using WPA encryption. For
 WEP or WPA, change the WiFi.begin() call accordingly.

 Circuit:
 * Board with NINA module (Arduino MKR WiFi 1010, MKR VIDOR 4000 and UNO WiFi Rev.2)
 * LED attached to pin 9

 created 25 Nov 2012
 by Tom Igoe
 */
#include <SPI.h>
#include <WiFiNINA.h>
#include <ArduinoJson.h>
#include <ArduinoHttpClient.h>
#include <stdio.h>
#include <string.h>

#include "arduino_secrets.h" 
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
char ssid[] = SECRET_SSID;        // your network SSID (name)
char pass[] = SECRET_PASS;    // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0;                 // your network key index number (needed only for WEP)

char serverAddress[] = "192.168.0.16";  // server address from Wifi. You can look up this adress in the settings
int port = 8888;
WiFiServer server(80);

WiFiClient wifi;
HttpClient http = HttpClient(wifi, serverAddress, port);

char webpage[] = R"=====(
<html>

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SBB Fahrplan</title>
</head>

<body>
    <script>
        const handleSubmit = () => {
            const radioButtons = document.querySelectorAll('input[name="zug"]');

            const abfahrt = document.getElementById('abfahrt').value
            const ankunft = document.getElementById('ankunft').value
            
            let selectedButton;

            for (const radioButton of radioButtons) {
                if (radioButton.checked) {
                    selectedButton = radioButton.value;
                    if (selectedButton === 'false') {
                        selectedButton = false
                    }

                    if (selectedButton === 'true') {
                        selectedButton = true
                    }
                }
            }

            var myHeaders = new Headers();
            myHeaders.append("Content-Type", "application/json");

            var raw = JSON.stringify({
                from: abfahrt,
                to: ankunft,
                lastOne: selectedButton
            });

            var requestOptions = {
                method: 'POST',
                headers: myHeaders,
                body: raw,
                redirect: 'follow'
            };

            fetch("http://localhost:8888/getDataByTrip", requestOptions)
                .then(response => response.json())
                .then(result => console.log(result)) 
                .then(fetch("http://192.168.0.17/H?from=Zurich-HB&to=St-Gallen&lastOne=false", {
                    method: "GET"
                }))
        }
    </script>
    <h2>SBB Fahrplan</h2>

    <label for="abbh">Abfahrts Bahnhof:</label>
    <input type="text" id="abfahrt" name="Abfahrts Bahnhof" placeholder="Abfahrts Bahnhof">

    <label for="anbh">Ankunfts Bahnhof:</label>
    <input type="text" id="ankunft" name="Ankunfts Bahnhof" placeholder="Ankunfts Bahnhof">

    <input type="radio" id="nzug" name="zug" value="false">
    <label for="nzug">nächster Zug</label>
    <input type="radio" id="lzug" name="zug" value="true">
    <label for="lzug">letzter Zug</label>
    <br><br>
    <button onclick="handleSubmit()">ok</button>
     <br><br>
    <button onclick="handleTest()">Test</button>

</body>

</html>
)=====";

void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your board's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
  // print where to go in a browser:
  Serial.print("To see this page in action, open a browser to http://");
  Serial.println(ip);
}

int status = WL_IDLE_STATUS;

void setup() {
  Serial.begin(9600);      // initialize serial communication
  pinMode(9, OUTPUT);      // set the LED pin mode

//char *string =  "?from=Zurich-HB&to=Bern&lastOne=false";

  // check for the WiFi module:
  if (WiFi.status() == WL_NO_MODULE) {
    Serial.println("Communication with WiFi module failed!");
    // don't continue
    while (true);
  }

  String fv = WiFi.firmwareVersion();
  if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
    Serial.println("Please upgrade the firmware");
  }

  // attempt to connect to WiFi network:
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to Network named: ");
    Serial.println(ssid);                   // print the network name (SSID);

    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    status = WiFi.begin(ssid, pass);
    // wait 10 seconds for connection:
    delay(10000);
  }
  server.begin();                           // start the web server on port 80
  printWifiStatus();                        // you're connected now, so print out the status
}

void loop() {
  WiFiClient client = server.available();   // listen for incoming clients

  if (client) {                             // if you get a client,
    Serial.println("new client");           // print a message out the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    while (client.connected()) {            // loop while the client's connected
      if (client.available()) {             // if there's bytes to read from the client,
       char c = client.read();             // read a byte, then
      Serial.write(c);                    // print it out the serial monitor
        if (c == '\n') {                    // if the byte is a newline character

          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println();

            // the content of the HTTP response follows the header:
            // client.print("Click <a href=\"/H\">here</a> turn the LED on pin 9 on<br>");
            client.print(webpage);

            // The HTTP response ends with another blank line:
            client.println();
            // break out of the while loop:
            break;
          } else {    // if you got a newline, then clear currentLine:
            currentLine = "";
          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }

        // Check to see if the client request was "GET /H" or "GET /L":
        if (currentLine.endsWith("GET /H")) {
         //digitalWrite(LED_BUILTIN, HIGH);             // GET /H turns the LED on
         
//           parseGetRequest("?from=Zurich-HB&to=Bern&lastOne=false");
         
 DynamicJsonDocument postMessage(2048);
 postMessage["from"] = "Zurich-HB";
 postMessage["to"] = "Bern";
 postMessage["lastOne"] = "false";
  
 String jsonBody;
 serializeJson(postMessage, jsonBody); 

 Serial.println("making POST request");
 String contentType = "application/json";

 http.post("/getDataByTrip", contentType, jsonBody);
  
 // read the status code and body of the response
 int statusCode = http.responseStatusCode();
 String response = http.responseBody();

  Serial.print("Status code: ");
  Serial.println(statusCode);
  Serial.print("Response: ");
  Serial.println(response);
  
    delay(4000);

        }
        if (currentLine.endsWith("GET /L")) {
          digitalWrite(LED_BUILTIN, LOW);                // GET /L turns the LED off
        }
      }
    }
    
    // close the connection:
    client.stop();
    Serial.println("client disconnected");
  }
}

this comes from that part of your code:

you spit out char by char the message you get from the client

note that there is also

➜ so you accumulate in currentLine the message you are receiving.

That's the buffer you need to parse before it's getting emptied with the

          } else {    // if you got a newline, then clear currentLine:
           <== YOU WANT TO CHECK HERE IF currentLine STARTS WITH GET AND EXTRACT THE DATA
            currentLine = "";
          }

Since it's in a String, you can use the String class functions to find the data you want to extract

Hi, Thanks for your reply. I will try to do something

So I could get the url now without problems:

          if (currentLine.startsWith("GET /H?from=")) {
            httpGetUrl += currentLine;
            
            httpGetUrl.remove(0, 7);
            int http = httpGetUrl.indexOf(" HTTP/1.1");
            httpGetUrl.remove(http, 9);

            
            Serial.print("URL: ");
            Serial.println(httpGetUrl);

  for (int i = 0; i < sizeof(tests) / sizeof(*tests); i++) {
    Serial.print("parsing \"");
    Serial.print(tests[i]);

    // copy test[i] into the buffer
    // because the parser overwrites what is i the string it is passed. 
    strcpy(buf, tests[i]);

    // parse the buffer into params[][]
    int resultsCt = parseUrlParams(buf, params, 5, true);

    // print off the results;

    Serial.print("\" produced ");
    Serial.print(resultsCt);
    Serial.print(" parameters:");
    Serial.println();

    for (int i = 0; i < resultsCt; i++) {
      Serial.print("param ");
      Serial.print(i);
      Serial.print(" name \"");
      Serial.print( params[i][0]);
      Serial.print("\", param \"");
      Serial.print( params[i][1]);
      Serial.print("\".");
      Serial.println();
    }
    Serial.println();
  }

           }

But now I want to put that string into this array here:

const char *tests[] = {};

Do you have a suggestion on how to do that?

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.