C URLencode库(支持Unicode)?

我需要一个可以对一个字符串/ char数组进行URL编码的库.

现在,我可以像这里一样对ASCII数组进行十六进制编码:
http://www.codeguru.com/cpp/cpp/cpp_mfc/article.php/c4029

但我需要一些适用于Unicode的东西.
注意:在Linux和Windows上!

CURL非常好:

char *encodedURL = curl_easy_escape(handle,WEBPAGE_URL,strlen(WEBPAGE_URL));

但首先,它需要CURL,它也不具备unicode能力,正如strlen所看到的那样

解决方法

如果我正确地阅读了这个任务并且你想自己这样做,而不是使用curl我认为我有一个解决方案(sssuming UTF-8),我认为这是一种符合URL和编码查询字符串的可移植方式:
#include <boost/function_output_iterator.hpp>
#include <boost/bind.hpp>
#include <algorithm>
#include <sstream>
#include <iostream>
#include <iterator>
#include <iomanip>

namespace {
  std::string encimpl(std::string::value_type v) {
    if (isalnum(v))
      return std::string()+v;

    std::ostringstream enc;
    enc << '%' << std::setw(2) << std::setfill('0') << std::hex << std::uppercase << int(static_cast<unsigned char>(v));
    return enc.str();
  }
}

std::string urlencode(const std::string& url) {
  // Find the start of the query string
  const std::string::const_iterator start = std::find(url.begin(),url.end(),'?');

  // If there isn't one there's nothing to do!
  if (start == url.end())
    return url;

  // store the modified query string
  std::string qstr;

  std::transform(start+1,// Append the transform result to qstr
                 boost::make_function_output_iterator(boost::bind(static_cast<std::string& (std::string::*)(const std::string&)>(&std::string::append),&qstr,_1)),encimpl);
  return std::string(url.begin(),start+1) + qstr;
}

除了boost之外,它没有非标准的依赖关系,如果你不喜欢boost依赖,那么删除并不难.

我测试了它:

int main() {
    const char *testurls[] = {"http://foo.com/bar?abc<>de??90   210fg!\"$%","http://google.com","http://www.unicode.com/example?großpösna"};
    std::copy(testurls,&testurls[sizeof(testurls)/sizeof(*testurls)],std::ostream_iterator<std::string>(std::cout,"\n"));
    std::cout << "encode as: " << std::endl;
    std::transform(testurls,"\n"),std::ptr_fun(urlencode));
}

这一切似乎都有效:

http://foo.com/bar?abc<>de??90   210fg!"$%
http://google.com
http://www.unicode.com/example?großpösna

变为:

http://foo.com/bar?abc%3C%3Ede%3F%3F90%20%20%20210fg%21%22%24%25
http://google.com
http://www.unicode.com/example?gro%C3%9Fp%C3%B6sna

哪些方块与这些examples

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...