Go Down

Topic: Improvement Suggestion for code example in WiFiClient Reference Page (Read 863 times) previous topic - next topic


I hope this is the right place to post documentation updates/recommendations.

If you try to use the Arduino WifiClient class example code from the reference documentation, it will likely fail on most modern websites. This is because the example does not pass the Host request header in the GET request, so many sites will return an HTTP 400 Bad Request error or 500 Domain Not Found error instead of the expected 200 OK. The HTTP 1.1 specification (and many HTTP 1.0 requests are upgraded to 1.1 nowadays) explicitly requires the Host header to be passed: https://tools.ietf.org/html/rfc7230#section-5.4.

If you are testing without adequate logging (which seems common for new Arduino tinkerers like me), this can take quite some time to discover and figure out why your requests are failing. The Host header is automatically passed by default when using curl, Postman and other web API testing tools so this makes the troubleshooting process even harder. It took me some serious digging to discover why that the Host header was the underlying issue and I even have a background in this stuff.

I'd recommend a mentiond of this is added to to the example code to highlight this problem, something like "Pass a Host header with the desired domain (required by many webservers)", preferably commented in the code as shown below:

Code: [Select]

 else {
    Serial.println("Connected to wifi");
    Serial.println("\nStarting connection...");
    // if you get a connection, report back via serial:
    if (client.connect(server, 80)) {
      // Make a HTTP request:
      client.println("GET /search?q=arduino HTTP/1.0");
      // Pass a Host header with the desired domain (required by many webservers)
      client.println("Host: google.com");

Please let me know what you think. Thanks!


Thank you. I think you just saved me alot of grief.

But what does one do if connecting to a home grown server on a laptop? How do I get a domain name for it?


Nevermind, an IPAddress appears to be accepted as well as a domain name

Go Up