Search code examples
pythonhttpgeturllib2

How do I create a GET request with parameters?


By default, it seems (for me) that every urlopen() with parameters seems to send a POST request. How can I set the call to send a GET instead?

import urllib
import urllib2

params = urllib.urlencode(dict({'hello': 'there'}))
urllib2.urlopen('http://httpbin.org/get', params)

urllib2.HTTPError: HTTP Error 405: METHOD NOT ALLOWED


Solution

  • you could use, much the same way that post request:

    import urllib
    import urllib2
    
    params = urllib.urlencode({'hello':'there', 'foo': 'bar'})
    urllib2.urlopen('http://somesite.com/get?' + params)
    

    The second argument should only be supplied when making POST requests, such as when sending a application/x-www-form-urlencoded content type, for example.