C&C++   发布时间:2019-10-05  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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 URLencode库(支持Unicode)?全部内容,希望文章能够帮你解决C URLencode库(支持Unicode)?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。