Convert dictionary to HTTP POST

  • Thread starter Laszlo Zsolt Nagy
  • Start date
L

Laszlo Zsolt Nagy

Hello,

How can I convert a dictionary into a HTTP POST string?
I have an example below, but this is not working correctly for special
characters. (" ' and others). In other words, if I use "Bessy's cat"
instead of "Bessy" then the http server will parse that to "Bessy's cat"
Probably the problem is that I should not use urllib.quote but something
else.
Can you please advise?

Laszlo

form_values = {'name':'Bessy','age':'10','gender':'female'}
for key,value in form_values.iteritems():
values.append('%s=%s' % (urllib.quote(key),urllib.quote(value)) )

values.append('x=33')
values.append('y=14')
post_data = ('&'.join(values)).replace('/','%2F')
txheaders = {

'Accept':'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5',
'Accept-Language':'en,hu;q=0.8,en-us;q=0.5,hu-hu;q=0.3',
'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
}
req = urllib2.Request(url, post_data, txheaders)
u = urllib2.build_opener()
req.add_data(post_data)
page2 = self.download(action,post_data,{
'Content-Type': 'application/x-www-form-urlencoded'
})
openerdirector = u.open(req)
data = openerdirector.read()
 
S

Sybren Stuvel

Laszlo Zsolt Nagy enlightened us with:
How can I convert a dictionary into a HTTP POST string? I have an
example below, but this is not working correctly for special
characters. (" ' and others).

URL-quote it.
In other words, if I use "Bessy's cat" instead of "Bessy" then the
http server will parse that to "Bessy's cat"

The HTTP server won't perform HTML-quoting out of thin air.
Probably the problem is that I should not use urllib.quote but
something else.

URL-quoting is the right thing to do:

In [1]: import urllib

In [2]: urllib.quote("Bessy's cat")
Out[2]: 'Bessy%27s%20cat'

If you want to give yourself an example of how it's done, run a
network sniffer and post something to a website.

Sybren
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top