urlencode提供HTTP错误403:FORBIDDEN

时间:2014-01-28 05:08:33

标签: python urlencode

callurl = "http://vgintnh116:8001/master_data/"
params = urllib.urlencode({'res': 'arovit', 'qfields': 'prod' })
f = urllib2.urlopen(callurl, params)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/u/vgtools2/python-2.6.5/lib/python2.6/urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "/u/vgtools2/python-2.6.5/lib/python2.6/urllib2.py", line 397, in open
    response = meth(req, response)
  File "/u/vgtools2/python-2.6.5/lib/python2.6/urllib2.py", line 510, in http_response
    'http', request, response, code, msg, hdrs)
  File "/u/vgtools2/python-2.6.5/lib/python2.6/urllib2.py", line 435, in error
    return self._call_chain(*args)
  File "/u/vgtools2/python-2.6.5/lib/python2.6/urllib2.py", line 369, in _call_chain
    result = func(*args)
  File "/u/vgtools2/python-2.6.5/lib/python2.6/urllib2.py", line 518, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: FORBIDDEN


But it works with - 
callurl = "http://vgintnh116:8001/master_data/res=arovit&qfields=prod"
f = urllib2.urlopen(callurl)

请帮忙。我想使用urlencode来避免处理空格和额外的字符。

2 个答案:

答案 0 :(得分:2)

如果你传递第二个参数(data),请求将是POST而不是GET。

此外,Python中的字典没有顺序。为了保证订单,您应该使用序列。

callurl = "http://vgintnh116:8001/master_data/"
params = urllib.urlencode([('res', 'arovit'), ('qfields', 'prod')])
f = urllib2.urlopen(callurl + params)

答案 1 :(得分:1)

来自urllib2 documentation

  

数据时,HTTP请求将是POST而不是GET   参数提供

在您的工作示例中,您正在发出GET请求。