While I generally agree with the last poster who says that you should try to use a tested library, I was unsuccessful in finding a lightweight library (curl was too heavy for me). Plus, I'm running in a special multi-threaded environment where I need to have very good accounting of my memory management. So, I wrote this snippet to do url-encoding, adapted from other code I found on the web (
http://www.gidforums.com/t-2615.html). Hope it helps the next guy find what he's looking for faster. Note that it's conservative and encodes everything that's not a number or a letter, but urldecoders will generally work with that.
template <class type> //template usage to allow multiple types of parameters
void dec_to_hex(type _num, char *hdigits)
{
const char *hlookup = "0123456789ABCDEF";
if(_num<0) _num *= -1;
char mask = 0x000f;
hdigits[1] = hlookup[mask & _num];
hdigits[0] = hlookup[mask & (_num >> 4)];
return;
}
void urlencode(std::string &str) {
size_t pos = 0;
std::string replacement;
for ( ; pos < str.length(); pos++) {
if (!isalnum(str[pos])) {
char dec[2];
dec_to_hex(str[pos], dec);
std::string replacement = "%" + std::string(dec, 2);
str.replace(pos, 1, replacement);
}
}
}