尝试在 Python 中使用 urllib2 发送“Post”请求时出现错误“BadStatusLine”

问题描述 投票:0回答:1

我需要在 IronPothon 2.7 中发送 Post 请求。 为此,我使用 urllib2 库。 处理响应时发生 BadStatusLine 错误 发送Get请求时没有出现这样的错误。 先感谢您 这是我的 Python 代码:

import urllib
import urllib2
import socket
import json
import httplib
url = "http://ros-adm.avanpost.local/api/v1/documents/bulk"
timeout = 300
socket.setdefaulttimeout(timeout)
req = urllib2.Request(url)
req.add_header('Content-Type', 'application/json')
req.add_header('Accept-Charset', 'utf-8')
req.add_header('Accept', 'application/json')
req.add_header('X-API-KEY', '6ed525532194418396411f15ad68a69a')
req.add_header('User-Agent','Mozilla/5.0')
req.add_header('Cache-Control', 'no-cache')
req.add_header('Accept-Encoding', 'gzip, deflate, br')
req.add_header('Connection', 'keep-alive')
req.add_header('Content-Length', '2890')
values = {"GroupType": "Block_user_account", "Documents": [{"DocumentId": "163", "SubjectId": "49","AuthorId": "50185c12-bd53-410c-8930-bd840920f3ba"," Fields": [{"Name": "DateTo", "Value": "2024-03-03","Type": "string"}],"DocType": "Add_field","FormType": "test" ,"Comment": "","IsDraft": "False"}]}
body = json.dumps(values)
post_data = body.encode("utf-8")
req.add_data(post_data)
try:
     r = urllib2.urlopen(req)
     data = json.loads(r.read().decode('utf-8'))
     r.close()
except urllib2.HTTPError, e:
     Logger.LogError(str(e.code))
     Logger.LogError(str(e.msg))
     Logger.LogError(str(e.hdrs))
     Logger.LogError(str(e.fp))
except urllib2.URLError, e:
     Logger.LogError(str(e.args))
except socket.timeout, e:
     Logger.LogError("socket: " + str(e))
except httplib.BadStatusLine, e:
      Logger.LogError("BadStatusLine!!!")
python json post urllib2
1个回答
0
投票

BadStatusLine 错误通常表示服务器响应不是 urllib2 期望的格式的问题,可能是由于响应格式错误或连接问题造成的。由于它发生在 Post 请求而不是 Get 请求中,因此请检查服务器是否需要 Post 请求的特定格式,或者两者之间的处理是否存在差异。此外,请确保内容长度标头与帖子数据的实际大小匹配。尝试发送不带某些可选标头的请求来隔离问题,并确认服务器可以按预期处理您的请求。

© www.soinside.com 2019 - 2024. All rights reserved.