繁体   English   中英

使用JSON的POST在邮递员中有效,但在Python中不起作用

[英]POST with JSON works in Postman but not in Python

包含Json数据的发布因python(2.7或3.6)失败,抛出错误“ 500 Internal server error”,但可从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

如果我添加“ Content-Length”作为邮递员,则收到“ 400错误的请求”错误。 邮递员控制台中的POST请求/响应

POST请求可以在我的机器上使用“请求”第3方程序包来工作,但是不幸的是,实际环境无法安装“请求”,因此需要它与标准内置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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM