Arduino HTTP Client library

Overview

ArduinoHttpClient

Check Arduino status Compile Examples status Spell Check status

ArduinoHttpClient is a library to make it easier to interact with web servers from Arduino.

Derived from Adrian McEwen's HttpClient library

Dependencies

Usage

In normal usage, handles the outgoing request and Host header. The returned status code is parsed for you, as is the Content-Length header (if present).

Because it expects an object of type Client, you can use it with any of the networking classes that derive from that. Which means it will work with WiFiClient, EthernetClient and GSMClient.

See the examples for more detail on how the library is used.

Issues
  • IFTTT POST call failing with Return Code = -2 with WiFiSSLClient

    IFTTT POST call failing with Return Code = -2 with WiFiSSLClient

    Hi,

    Your library perfectly matches my needs to POST on IFTTT, I'm connecting thtrough WiFiSSLClient and have imported certificates :

    2019-04-14 14_56_44-WiFi101 _ WiFiNINA Firmware_Certificates Updater

    I can successfuly post from curl but no way to make it run from mkr1000, always returning -2 return code :

    SSID: BABYLON
    IP Address: 192.168.1.32
    making POST request
    Status code: -2
    Response: 
    Wait five seconds
    making POST request
    
    char serverAddress[] = HOSTIFTTT;  // server address
    int port = 443;
    
    WiFiSSLClient wifi;
    HttpClient client = HttpClient(wifi, serverAddress, port);
    int status = WL_IDLE_STATUS;
    

    Here is the loop source code in case it can help :

    void loop() {
      Serial.println("making POST request");
      String contentType = "application/json";
      String postData = "{\"key1\": \"toto\"}";
    
      client.post("/trigger/test/with/key/MYPRIVATEKEY", contentType, postData);
    
      // 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);
    }
    

    I just can't figure out what's wrong with my code 😿

    ANy help would be greatly appreciated 🙏

    opened by adriens 27
  • Add support for chunked encoding and larger bodies

    Add support for chunked encoding and larger bodies

    This adds support for chunked transfer encodings and larger body writes. It also makes HttpClient::responseBody() more robust, similar to what #7 does.

    Replaces / conflicts with #7 Fixes #3

    opened by zonque 26
  • Add .sendBody()

    Add .sendBody()

    With mult-line POST requests, there is currently no way to send a body except using a sendHeader() call. A sendBody() would be useful in this regard.

    The following code works, but is confusing to the end user:

    HttpClient http(netSocket, wemo.c_str(), port); // make an HTTP client
      http.connectionKeepAlive();             // keep the connection alive
      http.beginRequest();                    // start assembling the request
      http.post(route);                       // set the route
      // add the headers:
      http.sendHeader("Content-type", "text/xml; charset=utf-8");
      String soapAction = "\"urn:Belkin:service:basicevent:1#SetBinaryState\"";
      http.sendHeader("SOAPACTION", soapAction);
      http.sendHeader("Connection: keep-alive");
      http.sendHeader("Content-Length", soap.length());
      http.sendHeader("");                    // a blank line before the body
      http.sendHeader(soap);                  // add the body
      http.endRequest();                      // end the request
      Serial.println("request opened");
    

    Two suggested solutions:

    Either sendBody() simply calls sendHeader(), or sendBody() callas a blank sendHeader() to separate from the headers, then calls sendHeader() with the body.

    opened by tigoe 12
  • How to POST a request to a https-server

    How to POST a request to a https-server

    Hello,

    I trying around for a while to connect to a cloud server and do not get it working because I can only put In the address of the server without https:// - so I get back a HTTP-Statuscode of 301 (redirect). I also tried it with the https port 443 but the server is not open on port 443. Please help me to get my code working without the redirect. I need "https://api.server.com" instead of "api.server.com"

    status: waiting for information 
    opened by bob3150 8
  • SecKey length

    SecKey length

    Hey, currently the SecKey length is fixed to 21 chars (https://github.com/arduino-libraries/ArduinoHttpClient/blob/master/src/WebSocketClient.cpp#L39), but I've seen some examples (f.e. wikipedia article) using 24 chars. There doesn't seem to be a specification about the length, but I've stumbled upon libraries that expect the length of 24 chars (https://www.npmjs.com/package/uws).

    So, I'd suggest to make the SecKey length overwritable and maybe change the default length to 24 characters.

    opened by bkniffler 5
  • Allow custom headers between startRequest & endRequest

    Allow custom headers between startRequest & endRequest

    Changes

    This change allows users to build more complex requests with custom headers when using startRequest and endRequest. Calls to the get, post, put, and del helpers will end the request as they did before.

    Tests

    SimpleGet.ino:

    making GET request
    Status code: 200
    Response: OK
    Wait five seconds
    

    SimplePost:

    making POST request
    Status code: 200
    Response: OK
    Wait five seconds
    

    SimplePut:

    making PUT request
    Status code: 200
    Response: OK
    Wait five seconds
    

    SimpleDelete:

    making DELETE request
    Status code: 200
    Response: OK
    Wait five seconds
    
    opened by toddtreece 5
  • After first POST, status code hangs on -4

    After first POST, status code hangs on -4

    #define SERVER_IP "XXXX"
    #define SERVER_PORT 5000
    
    const byte mac[] = {
        0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
    
    EthernetClient ethernetClient;
    HttpClient client = HttpClient(ethernetClient, SERVER_IP, SERVER_PORT);
    
    void setup()
    {
        Serial.begin(9600);
       
        Ethernet.begin(mac);
        Serial.print(F("IP Address: "));
        Serial.println(Ethernet.localIP());
    }
    
    void loop()
    {
        sendData("somedataToSend");
        delay(4000);
    }
    
    void sendData(const char *dataToSend)
    {
        const char *contentType = "text/plain";
        client.post("/api/values", contentType, dataToSend);
    
        // read the status code and body of the response
        int statusCode = client.responseStatusCode();
    
        // HERE - without this line, the status after first success (200) is then always -4 forever. 
        String response = client.responseBody();
    
        Serial.print("Status code: ");
        Serial.println(statusCode);
    }
    

    I have simple REST API which accepts plain text at /api/values endpoint. The code above just every 4 seconds try to send some string (not important actual content).

    After sending POST request - i want to display status code. If the line commented with "HERE" is not present, after first succesfull call to API the API is not called anymore and response code is equal to -4.

    Why it is neccessary to read responseBody? Am i missing something to get this work ?

    Expected behavior: POST should be possible repeatedly without reading response from server at all.

    status: waiting for information 
    opened by petrnymsa 4
  • bump release to include ESP8266 fix?

    bump release to include ESP8266 fix?

    hiya thanks for fixing https://github.com/arduino-libraries/ArduinoHttpClient/pull/49 if someone could bump the relesae to 0.4.0 or whatever, it will propogate out!

    opened by ladyada 4
  • Bug:  Arduino - cant compile - multiple definitions

    Bug: Arduino - cant compile - multiple definitions

    Compiling debug version of 'xfinityRemoteControl' for 'Arduino/Genuino Mega w/ ATmega2560 (Mega 2560)'

    HttpClient.cpp.o (symbol from plugin): In function HttpClient::read() (.text+0x0): multiple definition of HttpClient::read() HttpClient.cpp.o (symbol from plugin)*: (.text+0x0): first defined here

    any idea?

    type: support 
    opened by geetee24 3
  • Bump actions/checkout from 2 to 2.3.4

    Bump actions/checkout from 2 to 2.3.4

    Bumps actions/checkout from 2 to 2.3.4.

    Release notes

    Sourced from actions/checkout's releases.

    v2.3.4

    v2.3.3

    v2.3.2

    Add Third Party License Information to Dist Files

    v2.3.1

    Fix default branch resolution for .wiki and when using SSH

    v2.3.0

    Fallback to the default branch

    v2.2.0

    Fetch all history for all tags and branches when fetch-depth=0

    v2.1.1

    Changes to support GHES (here and here)

    v2.1.0

    Changelog

    Sourced from actions/checkout's changelog.

    Changelog

    v2.3.1

    v2.3.0

    v2.2.0

    v2.1.1

    • Changes to support GHES (here and here)

    v2.1.0

    v2.0.0

    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    topic: infrastructure 
    opened by dependabot[bot] 3
  • POST request with Basic Authentication

    POST request with Basic Authentication

    I am trying to write data on the web app, via Arduino IoT 33 nano, using a POST request combined with basic authentication. But it is not working. GET request works perfectly and gets authentication from the web app.

    http.beginRequest();
    http.get("/");
    http.sendBasicAuth(DB_USER, DB_PASS);
    http.endRequest();
    

    This works. but...

    http.beginRequest();
    http.post(PostUrl, "text/plain", PostBody);
    http.sendBasicAuth(DB_USER, DB_PASS);
    http.endRequest();
    

    This doesn't work. PostUrl and PostBody are in a correct format, because the same POST request works with Postman and gets a success code. From the web app side, everything is running well, and verified via Postman. I want to know if there's something more needed for POST requests. Also there is no Arduino example given for POST request with Basic Authorization. The web app doesn't receive any authorization credentials.

    opened by meshedmangoes 3
  • sendInitialHeaders breaks session

    sendInitialHeaders breaks session

    We have been trying to test a connection with our server to POST some data.

    We are using https so initialising the library with using WiFISecureClient and ssl cert and setting port to 443 as you would expect for https.

    The connection has been failing consistently and digging into the source to find the issue we have discovered that the check:

               if (iServerPort != kHttpPort)
               {
                  iClient->print(":");
                  iClient->print(iServerPort);
               }
    

    causes the port to be appended to tje Host header. Control needs to be added to be able to suppress this as it can cause issues with some proxy setups. Or facility needs to be added to initialise kHttpPort so it can match the iServerPort.

    type: imperfection topic: code 
    opened by purplehorace 0
  • Connect Websocket client to Socket.IO server

    Connect Websocket client to Socket.IO server

    I'm currently trying to connect my Arduino Portenta H7 to a Socket.IO server, but I'm unable to establish a connection.

    Arduino code:

    #include <SPI.h>
    #include <Ethernet.h>
    #include <ArduinoHttpClient.h>
    
    // Enter a MAC address and IP address for your controller below.
    // The IP address will be dependent on your local network:
    byte mac[] = {
      0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
    };
    IPAddress ip(10, 0, 0, 100);
    
    EthernetClient ethernet;
    
    char serverAddress[] = "10.0.0.14/socket.io/?EIO=4&transport=websocket";  // server address
    int port = 8080;
    
    WebSocketClient client = WebSocketClient(ethernet, serverAddress, port);
    int count = 0;
    
    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
      }
      Serial.println("Ethernet WebServer Example");
    
      // start the Ethernet connection and the server:
      Ethernet.begin(mac, ip);
    
      // 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.");
      }
    }
    
    void loop() {
      Serial.println("starting WebSocket client");
      client.begin();
    
      while (client.connected()) {
        Serial.print("Sending hello ");
        Serial.println(count);
    
        // send a hello #
        client.beginMessage(TYPE_TEXT);
        client.print("hello ");
        client.print(count);
        client.endMessage();
    
        // increment count for next message
        count++;
    
        // check if a message is available to be received
        int messageSize = client.parseMessage();
    
        if (messageSize > 0) {
          Serial.println("Received a message:");
          Serial.println(client.readString());
        }
    
        // wait 5 seconds
        delay(5000);
      }
    
      Serial.println("disconnected");
    }
    

    Socket.IO Example Server:

    import socketio
    from aiohttp import web
    
    sio = socketio.AsyncServer()
    app = web.Application()
    sio.attach(app)
    
    
    async def index(request):
        with open("index.html") as f:
            return web.Response(text=f.read(), content_type="text/html")
    
    
    @sio.on("*")
    def catch_all(event, sid, data):
        print("Socket ID: ", sid)
        print(data)
    
    
    app.router.add_get("/", index)
    
    if __name__ == "__main__":
        web.run_app(app)
    

    Versions:

    • python-socketio: 5x
    • Engine.IO: 4
    • Socket.IO 5

    I also tried using arduinoWebSockets, but I couldn't get it to work with the Arduino Portenta H7. Any help is greatly appreciated.

    type: imperfection 
    opened by TannerGilbert 1
  • docs unclear on how to basis auth

    docs unclear on how to basis auth

    My code http.connectionKeepAlive(); http.beginRequest(); *piRetCode = http.get( strPath ); http.sendBasicAuth ( "user", "pw" ); http.sendHeader( HTTP_HEADER_CONNECTION, "keep-alive" ); http.sendHeader( "Cache-Control", "max-age=0" ); http.sendHeader( "Accept", "application/json" ); http.endRequest();

    but my server responds with a timeout 401....

    is my code correct?

    type: imperfection topic: documentation 
    opened by geetee24 0
  • Update state on connect

    Update state on connect

    HttpClient implements inherited Client::connect(IPAddress ip, uint16_t port) and Client::connect(const char *host, uint16_t port). The existing implementation is to simple: it does not update internal state variables iServerName, iServerAddressand iServerPort, but just invokes the wrapped client. This causes subsequent requests to be incorrect (e.g. wrong host header).

    This PR changes connect to also update state.

    type: imperfection topic: code 
    opened by episource 2
  • Why is server url/port in HttpClient constructor?

    Why is server url/port in HttpClient constructor?

    Feature request:

    The example shows a static instance of HttpClient - but the server/port is fixed. What if I need to talk to serveral different servers? It would be useful to be able to omit these from the constructor and then use something like "setHost(host, port)"

    type: enhancement topic: code 
    opened by svenyonson 1
Releases(0.3.2)
Owner
Arduino Libraries
This org contains the official Arduino Libraries. See @arduino for the tools (IDE, Pro IDE, CLI...)
Arduino Libraries
Arduino Arduino library for the CloudStorage server project. The library provides easy access to server-stored values and operations.

Arduino-CloudStorage Arduino/ESP8266 library that allows you to easly store and retreive data from a remote (cloud) storage in a key/value fashion. Cl

Gil Maimon 7 Jan 30, 2022
Anto client library for ESP8266-Arduino

Anto client library for ESP8266-Arduino ESP8266-AntoIO provides common and easy way to connect your ESP8266 to Anto.io IoT platform service. Stable ve

Anto.io Internet of Things platform 10 Dec 1, 2021
Arduino client library for websocket based communication with archer panels.

ArduinoArcherPanelClient Arduino client library for websocket based communication with archer panels. Archer Cloud panels provide you an easy and fast

byteAgenten 1 May 18, 2018
OAuth 1.0 client library for Arduino

Arduino_OAuth Library for Arduino OAuth 1.0 client library for Arduino. This library depends on ArduinoHttpClient and ArduinoBearSSL. License Copyrigh

Arduino Libraries 16 Apr 21, 2022
Arduino library for making an IHC in or output module using an Arduino

Introduction This is an Arduino library for making an IHC in or output module using an Arduino. (IHC controller is a home automation controller made b

Jens Østergaard Nielsen 2 Mar 26, 2020
ArduinoIoTCloud library is the central element of the firmware enabling certain Arduino boards to connect to the Arduino IoT Cloud

ArduinoIoTCloud What? The ArduinoIoTCloud library is the central element of the firmware enabling certain Arduino boards to connect to the Arduino IoT

Arduino Libraries 60 Jul 20, 2022
Arduino TopLevel Client for aliyun IoT Platform

运行于 arduino 的 阿里云 IoT 接入 SDK,在底层连接的基础上增加数据回调绑定、发送数据和事件等 api 的封装,免去自己解析数据的痛苦

芋头 112 Aug 8, 2022
MQTT client for Arduino

ArduinoMqtt About MQTT Client library for Arduino based on the Eclipse Paho project. This library bundles the C/C++ MQTTPacket library of the Eclipse

Oleg Kovalenko 59 Jul 21, 2022
Arduino client for the Serial To TCP Bridge Protocol PC side service

Arduino Serial to TCP Bridge Client Arduino client for the Serial To TCP Bridge Protocol gateway service. Open a TCP connection to a server from the A

Roan Brand 13 Apr 12, 2022
Websocket client for Arduino, with fast data send

Websocket client for Arduino, with fast data send This is a simple library that implements a Websocket client running on an Arduino. Rationale For our

Davide Monari 29 Aug 4, 2022
A library to simplify the process of getting and storing data to Antares IoT Platform through HTTP on ESP8266.

Antares ESP8266 HTTP This is the documentation for Antares ESP8266 library. This library is meant to simplify the process of retrieving and deploying

null 6 Jul 2, 2021
High level HTTP Request Library that gives a javascript fetch like API.

Fetch for Arduino fetch is a high level HTTP Request Library that gives you a javascript fetch like API. ResponseOptions options; options.method = "PO

ma.name 57 Aug 1, 2022
The Approximate Library is a WiFi Arduino library for building proximate interactions between your Internet of Things and the ESP8266 or ESP32

The Approximate Library The Approximate library is a WiFi Arduino Library for building proximate interactions between your Internet of Things and the

David Chatting 101 Jul 29, 2022
Arduino library for controlling the MCP2515 in order to receive/transmit CAN frames.

107-Arduino-MCP2515 Arduino library for controlling the MCP2515 in order to receive/transmit CAN frames. This library is prepared to interface easily

107-Systems 46 Aug 3, 2022
Arduino library for interfacing with any GPS, GLONASS, Galileo or GNSS module and interpreting its NMEA messages.

107-Arduino-NMEA-Parser Arduino library for interfacing with any GPS, GLONASS, Galileo or GNSS module and interpreting its NMEA messages. This library

107-Systems 12 May 16, 2022
Arduino library for providing a convenient C++ interface for accessing UAVCAN.

107-Arduino-UAVCAN Arduino library for providing a convenient C++ interface for accessing UAVCAN (v1.0-beta) utilizing libcanard. This library works f

107-Systems 49 Jul 24, 2022
Arduino web server library.

aWOT Arduino web server library. Documentation 1. Getting started Hello World Basic routing Application generator Serving static files 2. Guide Routin

Lasse Lukkari 235 Jul 21, 2022
Arduino, esp32 and esp8266 library for ABB (ex PowerOne) Aurora Inverter, implement a full methods to retrieve data from the Inverter via RS-485

ABB Aurora protocol You can refer the complete documentation on my site ABB Aurora PV inverter library for Arduino, esp8266 and esp32 I create this li

Renzo Mischianti 20 May 30, 2022
Arduino library for the MCP2515 CAN Controller

MCP2515 CAN Controller Library for Arduino Compatibility with the ACAN library This library is fully compatible with the Teensy 3.x ACAN library https

Pierre Molinaro 3 Oct 1, 2021