MS Access中ServerXMLHTTP60认证&特殊字符处理方案咨询
解决application/x-www-form-urlencoded请求中特殊字符的转义问题
问题核心是:application/x-www-form-urlencoded格式里,&是参数的分隔符,当密码这类参数直接包含&时,会被API服务器误解析为新参数的起始标记,导致认证参数不完整,最终触发认证失败。
你需要对所有放入请求体的参数值做URL编码,把特殊字符转换成对应的百分号编码格式(比如&转成%26)。VBA没有内置通用URL编码函数,你可以实现一个自定义函数来处理:
Private Function URLEncode(ByVal str As String) As String Dim bytes() As Byte Dim i As Integer Dim char As String bytes = StrConv(str, vbUtf8) For i = LBound(bytes) To UBound(bytes) char = Hex(bytes(i)) If Len(char) = 1 Then char = "0" & char Select Case bytes(i) ' 保留数字、字母和部分安全符号:-._~ Case 48 To 57, 65 To 90, 97 To 122, 45, 46, 95, 126 URLEncode = URLEncode & Chr(bytes(i)) Case Else URLEncode = URLEncode & "%" & char End Select Next i End Function
然后修改你的do_connect函数,对所有参数值调用这个编码函数:
Private Function do_connect() As Boolean Dim json_obj As Object Dim credential_str As String If m_password = "" Then do_connect = False Exit Function End If ' 对每个参数值执行URL编码 credential_str = "grant_type=password&username=" & URLEncode(m_username) & "&password=" _ & URLEncode(m_password) & "&client_id=" & URLEncode(m_client_id) & "&client_secret=" & URLEncode(m_client_secret) m_xml_auth.Open bstrMethod:="POST", bstrURL:=m_auth_url, varAsync:=False m_xml_auth.setRequestHeader bstrheader:="Content-Type", bstrValue:="application/x-www-form-urlencoded" m_xml_auth.send (credential_str) If m_xml_auth.Status <> 200 Then do_connect = False m_password = "" MsgBox "Error while authentication: " & m_xml_auth.responseText 'Err.Raise Number:=M_ERR_API_RESPONSE, _ 'DESCRIPTION:="Authentication failed - response-status: " & m_xml_auth.Status Else Set json_obj = JsonConverter.ParseJson(m_xml_auth.responseText) m_bearer_token = "Bearer " & json_obj("access_token") Debug.Print m_bearer_token do_connect = True End If End Function
补充说明
- 这个自定义
URLEncode函数遵循RFC 3986标准,对除安全字符外的所有字符做UTF-8编码,能覆盖&、=、@、空格等各类特殊字符的转义需求。 - 建议对所有参数值都编码,不只是密码——避免用户名、客户端ID等参数包含特殊字符时也出现同样问题。
内容的提问来源于stack exchange,提问作者Mr.Dev
相关产品推荐
相关产品推荐

