qwerty qwerty - 1 month ago 16
Python Question

POST request not passed

I tried to send POST query with this code:

def open(self, url, params):
self.__opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookielib.CookieJar()))
c = self.__opener.open(
urllib2.Request(
url,
urllib.urlencode(params),
{"User-agent": "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"}
)
)

Class.open('http://example.com', {'username': 'test'});


But server say to me that username field is empty.

urllib.Request('http://example.com?username=test');


it works perfectly. How to fix it?

Answer

You are sending the data in the request body; this is perfectly normal in a POST request. However, http://example.com?username=test is not a POST request; that's a GET instead.

You can do the same with urlencode(); just add it to the URL with ?:

c = self.__opener.open(
    urllib2.Request(
        url + '?' + urllib.urlencode(params),
        {"User-agent": "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"}
    )
)
Comments