如何将Shell脚本curl POST请求转为Python requests.post并解决域名解析错误
问题:Python requests.post 出现 socket.gaierror 错误怎么解决?
我有一段可成功获取JSON响应的Shell脚本curl POST请求代码:
ESCAPED_PASSWORD='hfsudfgi88' USERID=1234 AUTHO_HOST='blah.refdata.com' AUTH_URL="https://${AUTHO_HOST}/as/tok.oauth2" resp=$(curl --silent "${AUTH_URL}" --request POST \ -H "Host: ${AUTHO_HOST}" \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "grant_type=client_credentials&client_id=${USERID}&client_secret=${ESCAPED_PASSWORD}")
(注:原Shell代码中Content-Type存在拼写错误,已修正为正确的application/x-www-form-urlencoded)
我将其转换为Python的requests.post代码:
res = { "grant_type":"client_credentials", "client_id": USERID, "client_secret":ESCAPED_PASSWORD } # send post request response = requests.post(AUTH_URL, json=res)
但运行Python代码时出现错误:
socket.gaierror: [Errno -2] Name or service not known
解决步骤
1. 排查变量拼写与URL正确性
socket.gaierror本质是域名解析失败,优先检查以下变量问题:
- 核对Python代码中
AUTHO_HOST(注意是AUTHO而非AUTH)的拼写与赋值是否和Shell一致,原Shell中是AUTHO_HOST='blah.refdata.com',如果Python里拼写错误或未定义该变量,会导致AUTH_URL拼接错误。 - 打印
AUTH_URL的值确认是否为正确的https://blah.refdata.com/as/tok.oauth2,避免拼接时出现语法错误。
2. 修正请求提交格式
原curl用-d参数提交的是表单数据(application/x-www-form-urlencoded),但Python代码中用json=res会发送JSON格式请求体,不仅不符合原请求规范,还可能引发服务端异常。需要改为:
- 使用
data=res替代json=res,requests会自动设置正确的Content-Type请求头。
3. 验证域名解析能力
在运行Python代码的机器上,执行nslookup blah.refdata.com或ping blah.refdata.com,如果无法解析域名,说明机器DNS配置存在问题,需调整DNS服务器或检查网络连接。
修正后的Python代码示例
import requests # 正确定义所有变量,确保拼写与赋值无误 ESCAPED_PASSWORD = 'hfsudfgi88' USERID = 1234 AUTHO_HOST = 'blah.refdata.com' AUTH_URL = f"https://{AUTHO_HOST}/as/tok.oauth2" # 构造表单数据,与原curl的-d参数内容一致 form_data = { "grant_type": "client_credentials", "client_id": USERID, "client_secret": ESCAPED_PASSWORD } # 发送表单格式的POST请求 response = requests.post(AUTH_URL, data=form_data) # 打印响应内容调试 print(response.text)
内容的提问来源于stack exchange,提问作者jikf
相关产品推荐
相关产品推荐

