0

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
3
  • This isn't Python 3. There is no urllib2 in Python 3. And, while there is a urllib, it's just a package with modules in it, not a module with a class called Request. So, first tell us which version you're actually using. Commented Jul 24, 2014 at 17:56
  • @abarnert, sorry. I tried to interpret it in Python 2.7.5. Commented Jul 24, 2014 at 17:57
  • OK, next problem. In the first version, you're passing username=test (www-form-encoded) as the body. In the second version (I'm assuming you actually used urllib2.Request there, because there's no such thing as urllib.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. Commented Jul 24, 2014 at 18:02

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

3 Comments

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.
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?
@qwerty: that depends on the server; if the server accepts your GET request but rejects the POST, then stick with GET.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.