B4R Tutorial Downloading a Web page with ESP8266

Discussion in 'B4R Tutorials' started by Erel, Sep 1, 2016.

  1. Erel

    Erel Administrator Staff Member Licensed User

    Edit: use rHttpUtils2 instead: https://www.b4x.com/android/forum/threads/module-rhttputils2-http-client.74785/#content
    As a general rule, I recommend to use Raspberry Pi with B4J to interact with web servers or http clients. It is much more powerful and simpler to develop. The Arduino and ESP8266 strengths are in other domains.

    This small example sends a http request with WiFiSocket and reads the response with AsyncStreams.

    Code:
    Sub Process_Globals
       
    Public Serial1 As Serial
       
    Private wifi As ESP8266WiFi
       
    Private astream As AsyncStreams
       
    Private socket As WiFiSocket
    End Sub

    Private Sub AppStart
       Serial1.Initialize(
    115200)
       
    Log("AppStart")
       
    If wifi.Connect("dlink"Then 'change as needed
         Log("Connected to router")
       
    Else
         
    Log("Failed to connect")
         
    Return
       
    End If
       Connect(
    0)
    End Sub

    Sub Connect(unused As Byte)
       
    If socket.ConnectHost("example.com"80) = False Then
         
    Log("trying to connect again")
         CallSubPlus(
    "Connect"10000)
         
    Return
       
    End If
       
    Log("Connected to server")
       astream.Initialize(
    socket.Stream, "Astream_NewData""Astream_Error")
       
    Dim eol() As Byte = Array As Byte(1310)
       astream.Write(
    "GET / HTTP/1.1".GetBytes)
       astream.Write(eol)
       astream.Write(
    "Host: www.example.com".GetBytes)
       astream.Write(eol)
       astream.Write(
    "Connection: close".GetBytes)
       astream.Write(eol)
       astream.Write(eol)
    End Sub

    Sub Astream_NewData (Buffer() As Byte)
       
    Log(Buffer)
    End Sub

    Sub Astream_Error
       
    Log("Disconnected")
    End Sub
    The html page will be printed to the logs.

    This code depends on the following libraries:
    rESP8266, rESP8266WiFi and rRandomAccessFile.
     
    Last edited: Dec 21, 2017
  2. John Decowski

    John Decowski Member Licensed User

    I try to download simple website hosted by my own iis server and returns http error 400 bad request invalid verb

    Any ideas?
     
  3. Erel

    Erel Administrator Staff Member Licensed User

    You should use rHttpUtils2 instead of this code.
     
    John Decowski likes this.
Loading...
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice