nad*_*ads 3 python post json urllib2 internal-server-error
使用 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
Run Code Online (Sandbox Code Playgroud)
如果我添加“Content-Length”,则与邮递员收到“400 Bad request”错误相同。 Postman 控制台中的 POST 请求/响应
POST 请求使用我的机器上的“Requests”第 3 方包工作,但不幸的是实际环境无法安装“Requests”,因此需要它与标准内置 python 模块一起使用。带有内置 GET 模块的 python 脚本也可以正常工作。我将不胜感激任何有关问题的帮助。
您将Content-Type
标头设置为 ,application/json
但将数据发送为application/x-www-form-urlencoded
。这可能是 HTTP 400 响应的原因。
尝试将数据作为 JSON 字符串发送:
#!/usr/bin/env python
import json
import urllib2
url = 'http://httpbin.org/post'
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,
}
try:
data = json.dumps(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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3332 次 |
最近记录: |