From d73940758a8fcb6e05d99fc7fcfa1978bec5ee2e Mon Sep 17 00:00:00 2001 From: Sandeep Mistry Date: Mon, 8 Apr 2019 15:05:59 -0400 Subject: [PATCH] Add URL Encoder class --- keywords.txt | 3 +++ src/ArduinoHttpClient.h | 1 + src/URLEncoder.cpp | 53 +++++++++++++++++++++++++++++++++++++++++ src/URLEncoder.h | 25 +++++++++++++++++++ 4 files changed, 82 insertions(+) create mode 100644 src/URLEncoder.cpp create mode 100644 src/URLEncoder.h diff --git a/keywords.txt b/keywords.txt index 27cd516..1b4bd2c 100644 --- a/keywords.txt +++ b/keywords.txt @@ -9,6 +9,7 @@ ArduinoHttpClient KEYWORD1 HttpClient KEYWORD1 WebSocketClient KEYWORD1 +URLEncoder KEYWORD1 ####################################### # Methods and Functions (KEYWORD2) @@ -47,6 +48,8 @@ isFinal KEYWORD2 readString KEYWORD2 ping KEYWORD2 +encode KEYWORD2 + ####################################### # Constants (LITERAL1) ####################################### diff --git a/src/ArduinoHttpClient.h b/src/ArduinoHttpClient.h index 578733f..abb8494 100644 --- a/src/ArduinoHttpClient.h +++ b/src/ArduinoHttpClient.h @@ -7,5 +7,6 @@ #include "HttpClient.h" #include "WebSocketClient.h" +#include "URLEncoder.h" #endif diff --git a/src/URLEncoder.cpp b/src/URLEncoder.cpp new file mode 100644 index 0000000..7baf5a9 --- /dev/null +++ b/src/URLEncoder.cpp @@ -0,0 +1,53 @@ +// Library to simplify HTTP fetching on Arduino +// (c) Copyright Arduino. 2019 +// Released under Apache License, version 2.0 + +#include "URLEncoder.h" + +URLEncoderClass::URLEncoderClass() +{ +} + +URLEncoderClass::~URLEncoderClass() +{ +} + +String URLEncoderClass::encode(const char* str) +{ + return encode(str, strlen(str)); +} + +String URLEncoderClass::encode(const String& str) +{ + return encode(str.c_str(), str.length()); +} + +String URLEncoderClass::encode(const char* str, int length) +{ + String encoded; + + encoded.reserve(length); + + for (int i = 0; i < length; i++) { + char c = str[i]; + + const char HEX_DIGIT_MAPPER[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; + + if (isAlphaNumeric(c) || (c == '-') || (c == '.') || (c == '_') || (c == '~')) { + encoded += c; + } else { + char s[4]; + + s[0] = '%'; + s[1] = HEX_DIGIT_MAPPER[(c >> 4) & 0xf]; + s[2] = HEX_DIGIT_MAPPER[(c & 0x0f)]; + s[3] = 0; + + encoded += s; + } + } + + return encoded; +} + +URLEncoderClass URLEncoder; diff --git a/src/URLEncoder.h b/src/URLEncoder.h new file mode 100644 index 0000000..e1859ff --- /dev/null +++ b/src/URLEncoder.h @@ -0,0 +1,25 @@ +// Library to simplify HTTP fetching on Arduino +// (c) Copyright Arduino. 2019 +// Released under Apache License, version 2.0 + +#ifndef URL_ENCODER_H +#define URL_ENCODER_H + +#include + +class URLEncoderClass +{ +public: + URLEncoderClass(); + virtual ~URLEncoderClass(); + + String encode(const char* str); + String encode(const String& str); + +private: + String encode(const char* str, int length); +}; + +extern URLEncoderClass URLEncoder; + +#endif