ESP8266 URL Encode Decode Example

In this tutorial we are looking at URL encoding and decoding in ESP8266 or NodeMCU. URL encoding converts characters into a format that can be transmitted over the Internet so that web browser can handle it. URL encoding is required when you send HTTP GET requests.NodeMCU URL Encode Decode

What is URL ?

URL – Uniform Resource Locator

Web browsers request pages from web servers by using a URL.

The URL is the address of a web page, like: https://circuits4you.com

URL Encoding (Percent Encoding)

URLs can only be sent over the Internet using the ASCII character-set.

Since URLs often contain characters outside the ASCII set, the URL has to be converted into a valid ASCII format.

URL encoding replaces unsafe ASCII characters with a “%” followed by two hexadecimal digits.

URLs cannot contain spaces. URL encoding normally replaces a space with a plus (+) sign or with %20.

URL Encoding Function

String urlencode(String str)
{
    String encodedString="";
    char c;
    char code0;
    char code1;
    char code2;
    for (int i =0; i < str.length(); i++){
      c=str.charAt(i);
      if (c == ' '){
        encodedString+= '+';
      } else if (isalnum(c)){
        encodedString+=c;
      } else{
        code1=(c & 0xf)+'0';
        if ((c & 0xf) >9){
            code1=(c & 0xf) - 10 + 'A';
        }
        c=(c>>4)&0xf;
        code0=c+'0';
        if (c > 9){
            code0=c - 10 + 'A';
        }
        code2='\0';
        encodedString+='%';
        encodedString+=code0;
        encodedString+=code1;
        //encodedString+=code2;
      }
      yield();
    }
    return encodedString;
    
}

URL Decoding Function

String urldecode(String str)
{
    
    String encodedString="";
    char c;
    char code0;
    char code1;
    for (int i =0; i < str.length(); i++){
        c=str.charAt(i);
      if (c == '+'){
        encodedString+=' ';  
      }else if (c == '%') {
        i++;
        code0=str.charAt(i);
        i++;
        code1=str.charAt(i);
        c = (h2int(code0) << 4) | h2int(code1);
        encodedString+=c;
      } else{
        
        encodedString+=c;  
      }
      
      yield();
    }
    
   return encodedString;
}

h2int function

unsigned char h2int(char c)
{
    if (c >= '0' && c <='9'){
        return((unsigned char)c - '0');
    }
    if (c >= 'a' && c <='f'){
        return((unsigned char)c - 'a' + 10);
    }
    if (c >= 'A' && c <='F'){
        return((unsigned char)c - 'A' + 10);
    }
    return(0);
}

ESP8266 URL Encode and Decode

Enter your SSID and Password in code. and then upload.

/*
 * NodeMCU URLEncode Decode Example
 * https://circuits4you.com
 */
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

const char MAIN_page[] PROGMEM = R"=====(
<!DOCTYPE html>
<html>
<body>

<textarea rows="4" cols="50" name="urlData" form="usrform">
@@url@@</textarea>

  <form action="/form" id="usrform">
    <input type="submit" name="urlTask" value="URL Encode">
    <input type="submit" name="urlTask" value="URL Decode">
  </form>

<br>
<textarea rows="4" cols="50">@@data@@
</textarea>

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

//SSID and Password of your WiFi router
const char* ssid = "YOUR SSID";
const char* password = "YOUR PASSWORD";

ESP8266WebServer server(80); //Server on port 80

String urlData="", url="Enter URL here...";
//===============================================================
// This routine is executed when you open its IP in browser
//===============================================================
void handleRoot() {
 String s = MAIN_page; //Read HTML contents
 s.replace("@@data@@", urlData);
 s.replace("@@url@@", url); 
 server.send(200, "text/html", s); //Send web page
}
//===============================================================
// This routine is executed when you press submit
//===============================================================
void handleForm() {
 url = server.arg("urlData"); 
 String task = server.arg("urlTask");


 Serial.print("Task:");
 Serial.println(task);

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

 if(task=="URL Encode"){
    urlData = urlencode(url);
    Serial.print("Encoded URL:");
    Serial.println(urlData);
 }
 else
 {
    urlData = urldecode(url);
    Serial.print("Decoded URL:");
    Serial.println(urlData);
 }
 
  server.sendHeader("Location", "/");
  server.send(302, "text/plain", "Updated– Press Back Button");
}
//==============================================================
//                  SETUP
//==============================================================
void setup(void){
  Serial.begin(115200);
  
  WiFi.begin(ssid, password);     //Connect to your WiFi router
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  //If connection successful show IP address in serial monitor
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println("WiFi");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());  //IP address assigned to your ESP
 
  server.on("/", handleRoot);      //Which routine to handle at root location
  server.on("/form", handleForm); //form action is handled here

  server.begin();                  //Start server
  Serial.println("HTTP server started");
}
//==============================================================
//                     LOOP
//==============================================================
void loop(void){
  server.handleClient();          //Handle client requests
}
//==============================================================
//                     URL Encode Decode Functions
//==============================================================
String urldecode(String str)
{
    
    String encodedString="";
    char c;
    char code0;
    char code1;
    for (int i =0; i < str.length(); i++){
        c=str.charAt(i);
      if (c == '+'){
        encodedString+=' ';  
      }else if (c == '%') {
        i++;
        code0=str.charAt(i);
        i++;
        code1=str.charAt(i);
        c = (h2int(code0) << 4) | h2int(code1);
        encodedString+=c;
      } else{
        
        encodedString+=c;  
      }
      
      yield();
    }
    
   return encodedString;
}

String urlencode(String str)
{
    String encodedString="";
    char c;
    char code0;
    char code1;
    char code2;
    for (int i =0; i < str.length(); i++){
      c=str.charAt(i);
      if (c == ' '){
        encodedString+= '+';
      } else if (isalnum(c)){
        encodedString+=c;
      } else{
        code1=(c & 0xf)+'0';
        if ((c & 0xf) >9){
            code1=(c & 0xf) - 10 + 'A';
        }
        c=(c>>4)&0xf;
        code0=c+'0';
        if (c > 9){
            code0=c - 10 + 'A';
        }
        code2='\0';
        encodedString+='%';
        encodedString+=code0;
        encodedString+=code1;
        //encodedString+=code2;
      }
      yield();
    }
    return encodedString;
    
}

unsigned char h2int(char c)
{
    if (c >= '0' && c <='9'){
        return((unsigned char)c - '0');
    }
    if (c >= 'a' && c <='f'){
        return((unsigned char)c - 'a' + 10);
    }
    if (c >= 'A' && c <='F'){
        return((unsigned char)c - 'A' + 10);
    }
    return(0);
}

 

Testing

Open serial monitor and get the ip address.

Open ip address in web browser.

URL Encode

Enter some url text in text box and press URL Encode button. also observe serial monitor.

URL Decode

Enter some url text in text box and press URL Encode button. also observe serial monitor.

URL Encode Decode are useful for HTTP GET method.

Read More

 

Leave a Reply