【发布时间】:2019-03-21 15:42:12
【问题描述】:
使用 Json 数据发布失败,python(2.7 或 3.6)抛出错误“500 内部服务器错误”,但在 Postman 中有效。从 Windows 7 命令提示符运行 python 脚本。
#!/usr/bin/env python
import urllib
import urllib2
url = 'http://<server>:<port>/web/services/notes2'
cont_type = 'application/json; charset=utf-8'
user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36'
values = {
"LK_IN_BRANCH": "00123",
"LK_IN_ACCOUNT": "12345678",
"LK_IN_ENTRY_DATE": "20190315",
"LK_IN_ENTRY_TIME": "12300111",
"LK_IN_HOLD_DATE": "20190331",
"LK_IN_EMP_INITS": "QTC",
"LK_IN_COMMENT": "Comment from py script-notes2",
"LK_IN_USER_ID": "Hxxxxxxx",
"LK_IN_NOTE_GROUP": " "}
headers = {
"User-Agent": user_agent,
"Content-Type": cont_type,
"Accept": user_agent,
"Accept-Encoding": "gzip, deflate"}
try:
data = urllib.urlencode(values)
req = urllib2.Request(url, data, headers)
response = urllib2.urlopen(req)
json = response.read()
print json
except urllib2.URLError as e:
if hasattr(e, 'reason'):
print 'We failed to reach a server.'
print 'Reason: ', e.reason
if hasattr(e, 'code'):
print 'The server couldn\'t fulfill the request.'
print 'Error code: ', e.code
如果我添加“内容长度”与邮递员相同,则会收到“400 错误请求”错误。 POST request/response in Postman Console
POST 请求使用我机器上的“Requests”第 3 方包工作,但不幸的是实际环境无法安装“Requests”,因此需要它与标准的内置 python 模块一起使用。带有用于 GET 的内置模块的 python 脚本也可以正常工作。如有任何问题,我将不胜感激。
【问题讨论】:
标签: python json post urllib2 internal-server-error