Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7 Python:urllib2 put请求返回301错误_Python 2.7_Urllib2_Http Status Code 301_Put - Fatal编程技术网

Python 2.7 Python:urllib2 put请求返回301错误

Python 2.7 Python:urllib2 put请求返回301错误,python-2.7,urllib2,http-status-code-301,put,Python 2.7,Urllib2,Http Status Code 301,Put,我试图通过Python2.7的urllib2模块发出put请求。当我执行GET时,它工作得很好,但当我尝试将其转换为PUT时,它会返回一个301 http错误。 我的代码在上面: opener = urllib2.build_opener(urllib2.HTTPHandler) req = urllib2.Request(reqUrl) base64string = base64.encodestring('%s:%s' % (v_username, v_password)).replace(

我试图通过Python2.7的urllib2模块发出put请求。当我执行GET时,它工作得很好,但当我尝试将其转换为PUT时,它会返回一个301 http错误。 我的代码在上面:

opener = urllib2.build_opener(urllib2.HTTPHandler)
req = urllib2.Request(reqUrl)
base64string = base64.encodestring('%s:%s' % (v_username, v_password)).replace('\n', '')
req.add_header("Authorization", "Basic %s" % base64string)
req.add_header("Content-Type", "application/rdf+xml")
req.add_header("Accept", "application/rdf+xml")
req.add_header("OSLC-Core-Version", "2.0")
req.get_method = lambda: 'PUT'
req.allow_redirects=True
url = opener.open(req)
如果我抑制该行

req.get_method = lambda: 'PUT'
它可以工作,但它是一个get请求(或者如果我传递一些数据,它是一个post),但它必须是一个PUT,我不知道如何用这个模块来做不同的事情

错误是

urllib2.HTTPError: HTTP Error 301: Moved Permanently.

有人比我更了解这一点吗?我是REST请求的新手,有些特殊性对我来说还不清楚。

我不确定,但可能是urllib正在为GET而不是PUT自动处理301吗?根据,用户代理可以自动重定向GET,但不能重定向PUTs


似乎表明urllib确实会自动处理301重定向,并且似乎有可能在给定RFC的情况下,它不会自动处理PUT重定向。我想你应该找出重定向的目的地并重定向到那里。

谢谢Ken F,你帮助我理解了这个问题。我直接在urllib2.py文件中更改了处理程序(不确定它是否非常干净,但不管怎样),以便它可以处理PUT请求:

if (code in (301, 302, 303, 307) and m in ("GET", "HEAD")
            or code in (301, 302, 303) and m in ("POST", "PUT")):
事实上,当请求既不是GET也不是POST时,它会自动引发一个错误。我很惊讶我找不到其他有同样问题的人