Python请求XML API异常ConnectionError :('连接已中止。',BadStatusLine(“''”,))当xml大小增加时

时间:2017-10-06 05:31:11

标签: python xml python-requests

我正在尝试使用XML API。当我使用小型XML有效负载时,它工作正常。

以下是代码

import requests

xml = """<?xml version="1.0" encoding="ISO-8859-1"?>
     <!DOCTYPE MESSAGE SYSTEM "http://127.0.0.1:80/psms/dtd/messagev12.dtd">
     <MESSAGE VER="1.2">
     <USER USERNAME="xxxxx" PASSWORD="xxxx" />
     <CONTENT  UDH="0" CODING="1" TEXT="SAMPLE" PROPERTY="0" ID="1" TEMPLATE="">
     <ADDRESS FROM="XXXX" TO="XXXXXXXXXX" SEQ="0" TAG="test"/>
     ......
     ......
     </CONTENT>
     </MESSAGE>"""

     payload = {'data'   : xml,'action'   : 'send'}
     headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0',
               'Content-Type': 'application/xml'}
     response =  requests.post(url, params = payload, headers=headers)
     print response.status_code
     print response.content

当异常被引发时,XML随着更多数据的增加而变得越来越大

Traceback (most recent call last):
File "C:\Users\dell\Desktop\SMS XML\xml_sms_api.py", line 30, in <module>
response =  requests.post(url, params = payload, headers=headers)
File "C:\Python27\lib\site-packages\requests\api.py", line 110, in post
return request('post', url, data=data, json=json, **kwargs)
File "C:\Python27\lib\site-packages\requests\api.py", line 56, in request
return session.request(method=method, url=url, **kwargs)
File "C:\Python27\lib\site-packages\requests\sessions.py", line 488, in request
resp = self.send(prep, **send_kwargs)
File "C:\Python27\lib\site-packages\requests\sessions.py", line 609, in send
r = adapter.send(request, **kwargs)
File "C:\Python27\lib\site-packages\requests\adapters.py", line 473, in send
raise ConnectionError(err, request=request)
ConnectionError: ('Connection aborted.', BadStatusLine("''",))

在负载XML大小很小之前它完全正常工作。但API验证可在单个XML中处理多达5k个条目。

1 个答案:

答案 0 :(得分:0)

尝试各种选项后发现问题和解决方案。

由于XML在请求中以params形式提供,因此将URL编码到URL中。因此,当传递巨大的XML数据时,URL长度超过了限制。

因此将params更改为数据也是内容类型

payload = {'data'   : xml,'action'   : 'send'}
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0',
           'Content-Type': 'application/application/x-www-form-urlencoded'}
response =  requests.post(url, data = payload, headers=headers)