UrlEncode UrlDecode

 URL编码、解码

 

string URLDecode(string  &strSrc)
{
  string buffer = "";
  int len = strSrc.length();

  for (int i = 0; i < len; i++)
  {
      int j = i ;
      char ch = strSrc.at(j);
      if (ch == '%')
   {
  char tmpstr[] = "0x0__";
  int chnum;
  tmpstr[3] = strSrc.at(j+1);
  tmpstr[4] = strSrc.at(j+2);
  chnum = strtol(tmpstr, NULL, 16);  
  buffer += chnum;
  i += 2;
      }
   else if(ch == '+')
   {
    buffer += ' ';
   }
   else
   {
  buffer += ch;
      }
   }

   len=MultiByteToWideChar(CP_UTF8, 0, buffer.c_str (), -1, NULL,0);
    WCHAR * wszUtf8 = new WCHAR[len+1];
 if( wszUtf8 == NULL )
 {
  strSrc = "";
  return strSrc;
 }
    memset(wszUtf8, 0, len * 2 + 2);
 MultiByteToWideChar(CP_UTF8, 0, buffer.c_str (), -1, wszUtf8, len);

 len = WideCharToMultiByte(CP_ACP, 0,  wszUtf8, -1, NULL, 0, NULL, NULL);
 char *szUtf8=new char[len + 1];
 if( szUtf8 == NULL )
 {
  delete[] wszUtf8;
  strSrc = ""; 
  return strSrc;
 }
 memset(szUtf8, 0, len + 1);
 WideCharToMultiByte (CP_ACP, 0,  wszUtf8, -1,  LPSTR(szUtf8), len, NULL,NULL);

 strSrc = szUtf8;
 delete[] szUtf8;
 delete[] wszUtf8;

 return strSrc;
}


string URLEncode(string  &strSrc)
{
 int len=MultiByteToWideChar(CP_ACP, 0, strSrc.c_str (), -1, NULL,0);
    WCHAR * wszUtf8 = new WCHAR[len+1];
 if( wszUtf8 == NULL )
 {
  strSrc = "";
  return strSrc;
 }
    memset(wszUtf8, 0, len * 2 + 2);
 MultiByteToWideChar(CP_ACP, 0, strSrc.c_str (), -1, wszUtf8, len);

 len = WideCharToMultiByte(CP_UTF8, 0,  wszUtf8, -1, NULL, 0, NULL, NULL);
 char *szUtf8=new char[len + 1];
 if( wszUtf8 == NULL )
 {
  delete[] wszUtf8;
  strSrc = ""; 
  return strSrc;
 }
 memset(szUtf8, 0, len + 1);
 WideCharToMultiByte (CP_UTF8, 0,  wszUtf8, -1,  LPSTR(szUtf8), len, NULL,NULL);

 szUtf8[len]=0;
 string strResult = szUtf8;

 char num[4]; 

 //处理特殊字符,转化为%ASCII码的形式,‘ ’转为‘+’
 string::size_type index1 = 0 ;
 while ( (index1 =strResult.find_first_of( "/"< >%//^[]`+$,@:;/!#?=&", index1)) != string::npos )
 {           
  memset( num, 0, sizeof(num) );

  if( strResult[index1]==' ')
  {
   num[0] = '+';
   strResult.replace (index1, 1, num);
   index1+=1;
   continue;
  }
  sprintf_s( num, "%c%2x", '%', (strResult[index1]&255 ));
  strResult.replace (index1, 1, num);
  index1+=3;
 }
 
 strSrc =""; 
 for(unsigned i=0;i<strResult.length ();i++)
 {
  memset( num, 0, sizeof(num) );
  strResult[i]&=255;
  if( strResult[i] <= 32 || strResult[i]>= 123 )
  {
   strSrc+='%';
   sprintf_s( num, "%2x", strResult[i]&255 );
   strSrc+=num;
  }
  else
  {
   strSrc+=strResult[i];
  }
 }

 delete[] szUtf8;
 delete[] wszUtf8;

 return strSrc;

}

 

本文来自http://blog.youkuaiyun.com/hbu_dcf/archive/2009/01/04/3703372.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值