POST method in Python: errno 104

人走茶凉 提交于 2019-12-25 11:58:22

问题


I am trying to query a website in Python. I need to use a POST method (according to what is happening in my browser when I monitor it with the developer tools).

If I query the website with cURL, it works well:

curl -i --data "param1=var1&param2=var2" http://www.test.com

I get this header:

HTTP/1.1 200 OK
Date: Tue, 26 Sep 2017 08:46:18 GMT
Server: Apache/1.3.33 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 PHP/4.3.11
Transfer-Encoding: chunked
Content-Type: text/html

But when I do it in Python 3, I get an error 104.

Here is what I tried so far. First, with urllib (getting inspiration from this thread to manage to use a POST method instead of GET):

import re
from urllib import request as ur

# URL to handle request                                                                                      
url = "http://www.test.com"
data = "param1=var1&param2=var2"

# Build a request dictionary
preq = [re.findall("[^=]+", i) for i in re.findall("[^\&]+", data)]
dreq = {i[0]: i[1] if len(i) == 2 else "" for i in preq}

# Initiate request & add method
ureq = ur.Request(url)                                                                                     
ureq.get_method = lambda: "POST"                                                                           
# Send request                                                                                             
req = ur.urlopen(ureq, data=str(dreq).encode())                                                            

I did basically the same with requests:

import re
import requests

# URL to handle request                                                                                      
url = "http://www.test.com"
data = "param1=var1&param2=var2"

# Build a request dictionary
preq = [re.findall("[^=]+", i) for i in re.findall("[^\&]+", data)]
dreq = {i[0]: i[1] if len(i) == 2 else "" for i in preq}

# Initiate request & add method
req = requests.post(url, data=dreq)                                                            

In both cases, I get a HTTP 104 error:

ConnectionResetError: [Errno 104] Connection reset by peer

That I don't understand since the same request is working with cURL. I guess I misunderstood something with Python request but so far I'm stuck. Any hint would be appreciated!


回答1:


I've just figured out I did not pass data in the right format. I thought it needed to be store in a dict; that is not the case and it is therefore much more simple that what I tried previously.

With urllib:

req = ur.urlopen(ureq, data=str(data).encode())

With requests:

req = requests.post(url, data=data)


来源:https://stackoverflow.com/questions/46422307/post-method-in-python-errno-104

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!