Url编解码

本文介绍了如何使用C++编写URL编码(urlEncode)和解码(urlDecode)函数,以及在main函数中对字符串进行操作,展示如何将非ASCII字符转换为URL安全格式并保存到文件中。
摘要由CSDN通过智能技术生成
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <sstream>


std::string urlEncode(const std::string& strInput)
{
    static auto funcCheckAlpha = [=](unsigned char c) {
        bool bAlpha = false;
        if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'))
            bAlpha = true;
        return bAlpha;
    };
    std::ostringstream osOut;
    osOut.fill('0');
    osOut << std::hex;

    for (auto c : strInput) {
        if (funcCheckAlpha(c) || c == '-' || c == '_' || c == '.' || c == '~') {
            osOut << c;
        }
        else if (c == ' ') {
            osOut << '+';
        }
        else {
            osOut << '%' << std::setw(2) << int((unsigned char)c);
        }
    }

    return osOut.str();
}

std::string urlDecode(const std::string& strInput) {
    std::ostringstream osOut;

    for (size_t i = 0; i < strInput.length(); ++i) {
        if (strInput[i] == '%') {
            int hex;
            sscanf(strInput.substr(i + 1, 2).c_str(), "%x", &hex);
            osOut << static_cast<char>(hex);
            i += 2;
        }
        else if (strInput[i] == '+') {
            osOut << ' ';
        }
        else {
            osOut << strInput[i];
        }
    }

    return osOut.str();
}

unsigned char CharToHex(unsigned char x)
{
    return (unsigned char)(x > 9 ? x + 55 : x + 48);
}

int main() {
    //std::string strInput = "%E4%BD%A0%E5%A5%BD22";
    //std::string strInput("WeCom_4.1.16.6007%281%29--.exe");
    //std::string strInput = "%E5%91%98%E5%B7%A5++%E5%AF%86%E7%A0%81%E9%87%8D%E7%BD%AE%E8%BD%AF%E4%BB%B6%EF%BC%881%EF%BC%89.zip";
    std::string strInput("WeCom_4.1.16.6007%281%29--.exe");
    //std::string strInput = "%e4%bd%a0%e5%a5%bd%e5%95%8a22%e5%95%8a";
    std::string decoded = urlDecode(strInput);

    std::ofstream file("output.txt");
    if (file.is_open()) {
        file << "Src: \n\t" << strInput << "\n";
        file << decoded << "\n";

        std::cout << "File written successfully." << std::endl;
    }
    else {
        std::cout << "Failed to open file." << std::endl;
    }
    std::string encode = urlEncode(decoded);
    file << "encode: \n\t" << encode << "\n";
    file.close();
    return 0;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值