繁体   English   中英

如何在C ++中使用UTF-8字符解码URI

[英]How to decode an URI with UTF-8 characters in C++

我需要在C ++中解码URI。 我发现了几个有关此问题,但它们都无法处理UTF-8编码和重音(我对准确处理ASCII字符很感兴趣)。

然后,我使用了广泛使用的库,例如libcurl ...,但是它也无法解决UTF-8编码。 这就是我在做什么

string UriHelper::Decode(const string &encoded)
{
    CURL *curl = curl_easy_init();
    int outlength;
    char *cres = curl_easy_unescape(curl, encoded.c_str(), encoded.length(), &outlength);
    string res(cres, cres + outlength);
    curl_free(cres);
    curl_easy_cleanup(curl);
    return res;
}

问题是当应该将a%C3%A1e%C3%A9i%C3%ADo%C3%B3u%C3%BA解码为aáeéiÃoóuú时,它才应该被aáeéiíoóuú 如果我使用a%E1e%E9i%EDo%F3u%FA它可以正常工作。

有没有可以处理不同编码的URI并处理它们的库?

谢谢!

您的解码没有错。 问题是打印解码的URL。 打印到的输出设备配置为接受以ISO-8859-1(而不是UTF-8)编码的字符串。

将输出设备配置为接受以UTF-8编码的字符串,或者将解码的URL从UTF-8转换为ISO-8859-1。

正如Oswald所说的,问题不在于解码...而是我用来显示字符串的方法。 因为我真的不需要处理UTF-8字符串,所以我将继续他的第二个建议,并将其转换为ISO-8859-1。

从此答案中借用了这个想法(以及大部分代码)。 是否有办法将UTF8转换为iso-8859-1?

为此,我向iconv添加了一个依赖项。

这是我的UriHelper.h

#pragma once

using namespace std;

static class UriHelper
{
public:
    static string Encode(const string &source);
    static string Decode(const string &encoded);
};

这是我的UriHelper.cpp

#include "UriHelper.h"
#include <curl/curl.h>
#include <iconv.h>

string UriHelper::Encode(const string &source)
{
    CURL *curl = curl_easy_init();
    char *cres = curl_easy_escape(curl, source.c_str(), source.length());
    string res(cres);
    curl_free(cres);
    curl_easy_cleanup(curl);
    return res;
}

string UriHelper::Decode(const string &encoded)
{
    CURL *curl = curl_easy_init();
    int outlength;
    char *cres = curl_easy_unescape(curl, encoded.c_str(), encoded.length(), &outlength);
    string res(cres, cres + outlength);
    curl_free(cres);
    curl_easy_cleanup(curl);

    //if it's UTF-8, convert it to ISO_8859-1. Based on https://stackoverflow.com/questions/11156473/is-there-a-way-to-convert-from-utf8-to-iso-8859-1/11156490#11156490
    iconv_t cd = iconv_open("ISO_8859-1", "UTF-8");

    const char *in_buf = res.c_str();
    size_t in_left = res.length();

    char *output = new char[res.length() + 1];
    std::fill(output, output + res.length() + 1, '\0');
    char *out_buf = &output[0];
    size_t out_left = res.length();

    do {
        if (iconv(cd, &in_buf, &in_left, &out_buf, &out_left) == (size_t)-1) {
            //failed to convert, just return the value received from curl
            delete[] output;
            iconv_close(cd);
            return res;
        }
    } while (in_left > 0 && out_left > 0);

    string outputString(output);
    delete[] output;
    iconv_close(cd);

    return outputString;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM