带请求的HTTP-Post失败:BadStatusLine

时间:2016-04-24 03:12:47

标签: python post python-requests

我遇到以下代码的问题。在尝试使用POST-Request将文件上传到API时,我收到错误消息

File "upload.py", line 44, in <module>
    so.uploadData("./test.txt")
  File "upload.py", line 37, in uploadData
    req = requests.post("http://"+server, data=payload, headers=headers)
  File "/Library/Python/2.7/site-packages/requests/api.py", line 109, in post
    return request('post', url, data=data, json=json, **kwargs)
  File "/Library/Python/2.7/site-packages/requests/api.py", line 50, in request
    response = session.request(method=method, url=url, **kwargs)
  File "/Library/Python/2.7/site-packages/requests/sessions.py", line 468, in request
    resp = self.send(prep, **send_kwargs)
  File "/Library/Python/2.7/site-packages/requests/sessions.py", line 576, in send
    r = adapter.send(request, **kwargs)
  File "/Library/Python/2.7/site-packages/requests/adapters.py", line 412, in send
    raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: ('Connection aborted.', BadStatusLine("''",))

我的代码如下:

filedata= open(path, 'r')
payload = {'name': self.username, 'file':filedata}
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36', 'content-type': "multipart/form-data"}
req = requests.post("http://"+server, data=payload, headers=headers)

有没有人能解决这个问题?最好的问候

1 个答案:

答案 0 :(得分:2)

您的代码未构建有效的multipart / form-data POST请求 - 它正在构建application / x-www-form-urlencoded。覆盖Content-type标头不会更改数据的发布方式。服务器看到无效请求并断开连接,这会导致您在客户端中看到错误。

使用requests发布多部分/表单数据的最简单方法是使用files参数:

with open(path, 'rb') as filedata:
    payload = {'name': self.username}
    headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36'}
    req = requests.post(url, data=payload, headers=headers, files={'file': filedata})

这样requests将构造一个有效的multipart / form-data POST请求。

另一种方法,如果您没有明确要求使用multipart / form-data请求不覆盖Content-type标题:

with open(path, 'rb') as filedata:
    payload = {'name': self.username, 'file': filedata}
    headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36'}
    req = requests.post(url, data=payload, headers=headers)