Skip to content

Commit d739407

Browse files
committed
Add URL Encoder class
1 parent 4045c85 commit d739407

File tree

4 files changed

+82
-0
lines changed

4 files changed

+82
-0
lines changed

keywords.txt

+3
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
ArduinoHttpClient KEYWORD1
1010
HttpClient KEYWORD1
1111
WebSocketClient KEYWORD1
12+
URLEncoder KEYWORD1
1213

1314
#######################################
1415
# Methods and Functions (KEYWORD2)
@@ -47,6 +48,8 @@ isFinal KEYWORD2
4748
readString KEYWORD2
4849
ping KEYWORD2
4950

51+
encode KEYWORD2
52+
5053
#######################################
5154
# Constants (LITERAL1)
5255
#######################################

src/ArduinoHttpClient.h

+1
Original file line numberDiff line numberDiff line change
@@ -7,5 +7,6 @@
77

88
#include "HttpClient.h"
99
#include "WebSocketClient.h"
10+
#include "URLEncoder.h"
1011

1112
#endif

src/URLEncoder.cpp

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
// Library to simplify HTTP fetching on Arduino
2+
// (c) Copyright Arduino. 2019
3+
// Released under Apache License, version 2.0
4+
5+
#include "URLEncoder.h"
6+
7+
URLEncoderClass::URLEncoderClass()
8+
{
9+
}
10+
11+
URLEncoderClass::~URLEncoderClass()
12+
{
13+
}
14+
15+
String URLEncoderClass::encode(const char* str)
16+
{
17+
return encode(str, strlen(str));
18+
}
19+
20+
String URLEncoderClass::encode(const String& str)
21+
{
22+
return encode(str.c_str(), str.length());
23+
}
24+
25+
String URLEncoderClass::encode(const char* str, int length)
26+
{
27+
String encoded;
28+
29+
encoded.reserve(length);
30+
31+
for (int i = 0; i < length; i++) {
32+
char c = str[i];
33+
34+
const char HEX_DIGIT_MAPPER[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
35+
36+
if (isAlphaNumeric(c) || (c == '-') || (c == '.') || (c == '_') || (c == '~')) {
37+
encoded += c;
38+
} else {
39+
char s[4];
40+
41+
s[0] = '%';
42+
s[1] = HEX_DIGIT_MAPPER[(c >> 4) & 0xf];
43+
s[2] = HEX_DIGIT_MAPPER[(c & 0x0f)];
44+
s[3] = 0;
45+
46+
encoded += s;
47+
}
48+
}
49+
50+
return encoded;
51+
}
52+
53+
URLEncoderClass URLEncoder;

src/URLEncoder.h

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// Library to simplify HTTP fetching on Arduino
2+
// (c) Copyright Arduino. 2019
3+
// Released under Apache License, version 2.0
4+
5+
#ifndef URL_ENCODER_H
6+
#define URL_ENCODER_H
7+
8+
#include <Arduino.h>
9+
10+
class URLEncoderClass
11+
{
12+
public:
13+
URLEncoderClass();
14+
virtual ~URLEncoderClass();
15+
16+
String encode(const char* str);
17+
String encode(const String& str);
18+
19+
private:
20+
String encode(const char* str, int length);
21+
};
22+
23+
extern URLEncoderClass URLEncoder;
24+
25+
#endif

0 commit comments

Comments
 (0)