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?
Martijn Pieters
1.1m326 gold badges4.2k silver badges3.5k bronze badges
asked Jul 24, 2014 at 17:51
qwerty
2291 gold badge4 silver badges12 bronze badges
1 Answer 1
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)"}
)
)
answered Jul 24, 2014 at 18:03
Martijn Pieters
1.1m326 gold badges4.2k silver badges3.5k bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
abarnert
You could also use
urlparse.urlunparse or a similarly higher-level function instead of string manipulation, which would work if you, e.g., got a URL that already had a query string.qwerty
It's so strangely. Form action param is post. Please, see this repo: github.com/Ejz/Common/blob/master/carnage-bot/bot.py (urlopen method) I think it works, but why my code doesn't work?
Martijn Pieters
@qwerty: that depends on the server; if the server accepts your GET request but rejects the POST, then stick with GET.
lang-py
urllib2in Python 3. And, while there is aurllib, it's just a package with modules in it, not a module with a class calledRequest. So, first tell us which version you're actually using.username=test(www-form-encoded) as the body. In the second version (I'm assuming you actually usedurllib2.Requestthere, because there's no such thing asurllib.Request?), you're passing it in the query string. While many web services will treat the two as the same thing, there's no requirement that they do so.