Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Un-Escape String received via Post Data [duplicate]

Tags:

c++

http

I am writing a program, that has a small, self-written HTTP Server inside. Now i get Data via POST over the socket. My problem is, how do I unescape the String the best way in C++? I get Data like:

command=foo%26bar

but i want it to be

command=foo&bar

Whats the best way to achieve this in C++?

EDIT: If someone is interested in my solution, here it is:

void HttpServer::UnescapePostData(std::string & data) {
    size_t pos;    
    while ((pos = data.find("+")) != std::string::npos) {
        data.replace(pos, 1, " ");
    }
    while ((pos = data.find("%")) != std::string::npos) {
        if (pos <= data.length() - 3) {
            char replace[2] = {(char)(std::stoi("0x" + data.substr(pos+1,2), NULL, 16)), '\0'};
            data.replace(pos, 3, replace);
        }
    }
}
like image 980
Nidhoegger Avatar asked May 07 '26 21:05

Nidhoegger


1 Answers

Well, there is no formal definition of the right terminology, but this kind of process is generally describing as "unescaping", or "parsing" rather than escaping. You would like to parse the application/x-www-form-urlencoded-encoded string.

And the answer is rather boring: you just do it. That's all. application/x/www-form-urlencoded only does two things: replace spaces with "+" signs, and replace most other kind of punctuation (including the real "+" sign itself) with %xx, where xx is the octet in hexadecimal.

So, you just roll up your sleeves, and do it. Scan the string, replace the + character with a space, and replace each occurence of %xx with the single character, the evaluated hexadecimal octet. There's nothing particularly mysterious about the process. It is exactly what it appears to be.

like image 134
Sam Varshavchik Avatar answered May 10 '26 11:05

Sam Varshavchik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!