; 编码
MsgBox % URLEncode("中文")

URLEncode(Uri) {
  VarSetCapacity(Var, StrPut(Uri, "UTF-8"), 0)
  , StrPut(Uri, &Var, "UTF-8")
  , f := A_FormatInteger
  SetFormat, IntegerFast, H
  while Code := NumGet(Var, A_Index - 1, "UChar")
    if (Code >= 0x30 && Code <= 0x39 ; 0-9
      || Code >= 0x41 && Code <= 0x5A ; A-Z
      || Code >= 0x61 && Code <= 0x7A) ; a-z
      Res .= Chr(Code)
    else
      Res .= "%" . SubStr(Code + 0x100, -1)
  SetFormat, IntegerFast, %f%
  return Res
}

; 解码
MsgBox % URLDecode("%E4%B8%AD%E6%96%87")

URLDecode(url) {
  position := 1
  Loop {
    position := RegExMatch(url, "i)(?:%[0-9a-f]{2})+", code, position)
    if (position = 0)
      Break
    VarSetCapacity(binary, StrLen(code) // 3, 0)
    Loop, Parse, % SubStr(code, 2), % "%" 
      NumPut("0x" . A_LoopField, binary, A_Index - 1, "UChar")
    replacement := StrGet(&binary, "UTF-8")
    , url := RegExReplace(url, "i)(?:%[0-9a-f]{2})+", replacement, , 1, position)
    , position := position + StrLen(replacement)
  }
  Return url
}


/*   ; 不过滤123abc
UrlEncode(str, enc:="UTF-8") {
  hex := "00"
  , VarSetCapacity(buff, size:=StrPut(str, enc))
  , StrPut(str, &buff, enc)
  while(code:=NumGet(buff, A_Index - 1, "UChar")) && dllcall("msvcrt\swprintf", "str",hex, "str","%%%02X", "uchar",code, "cdecl")
    r .= hex
  return r
}
*/

/*   v2版
MsgBox(UrlEscape('中国'))

UrlEscape(url) {
  DllCall('shlwapi\UrlEscape', 'str', url, 'ptr*', 0, 'uint*', &l := 1, 'uint', f := 0xc2000)
  DllCall('shlwapi\UrlEscape', 'str', url, 'ptr', b := Buffer(l << 1), 'uint*', &l, 'uint', f)
  return StrGet(b)
}
*/

 

声明:站内资源为整理优化好的代码上传分享与学习研究,如果是开源代码基本都会标明出处,方便大家扩展学习路径。请不要恶意搬运,破坏站长辛苦整理维护的劳动成果。本站为爱好者分享站点,所有内容不作为商业行为。如若本站上传内容侵犯了原著者的合法权益,请联系我们进行删除下架。