You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将MS365 API访问的urllib代码转换为requests代码求助

使用Requests库替代urllib实现MS365 API的Token获取

原官方示例使用urllib库完成OAuth2客户端凭证模式的Token获取,以下是等价的Requests库实现:

import requests

tenantId = '00000000-0000-0000-0000-000000000000' # 替换为你的租户ID
appId = '11111111-1111-1111-1111-111111111111' # 替换为你的应用ID
appSecret = '22222222-2222-2222-2222-222222222222' # 替换为你的应用密钥

url = f"https://login.microsoftonline.com/{tenantId}/oauth2/token"
resourceAppIdUri = 'https://api.securitycenter.microsoft.com'

body = {
    'resource': resourceAppIdUri,
    'client_id': appId,
    'client_secret': appSecret,
    'grant_type': 'client_credentials'
}

# 发送POST请求,Requests自动处理表单编码和字节转换
response = requests.post(url, data=body)
response.raise_for_status() # 可选:主动抛出HTTP错误状态码异常,便于调试
json_response = response.json()
aad_token = json_response["access_token"]

关键对应关系说明:

  • urllib中urllib.parse.urlencode(body).encode("utf-8")的表单编码操作,Requests会自动处理,只需将字典直接传给data参数即可
  • urllib.request.Request(url, data) + urllib.request.urlopen(req) 对应 Requests 的 requests.post(url, data=body)
  • json.loads(response.read()) 对应 Requests 内置的 response.json() 方法,直接返回解析后的JSON字典

内容的提问来源于stack exchange,提问作者Josh Ackland

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 16:06:27