csatblogspotdotcom

Monday, March 28, 2016

Python urllib2使用POST还是GET

参考:https://docs.python.org/2/library/urllib2.html 如下 节选片段1: class urllib2.Request(url[, data][, headers][, origin_req_host][, unverifiable]) This class is an abstraction of a URL request. url should be a string containing a valid URL. data may be a string specifying additional data to send to the server, or None if no such data is needed. Currently HTTP requests are the only ones that use data; the HTTP request will be a POST instead of a GET when the data parameter is provided. data should be a buffer in the standard application/x-www-form-urlencoded format. The urllib.urlencode() function takes a mapping or sequence of 2-tuples and returns a string in this format. 节选片段2: HTTPRedirectHandler.redirect_request(req, fp, code, msg, hdrs, newurl) Return a Request or None in response to a redirect. This is called by the default implementations of the http_error_30*() methods when a redirection is received from the server. If a redirection should take place, return a new Request to allow http_error_30*() to perform the redirect to newurl. Otherwise, raise HTTPError if no other handler should try to handle this URL, or return None if you can’t but another handler might. Note The default implementation of this method does not strictly follow RFC 2616, which says that 301 and 302 responses to POST requests must not be automatically redirected without confirmation by the user. In reality, browsers do allow automatic redirection of these responses, changing the POST to a GET, and the default implementation reproduces this behavior. 节选片段3: 20.6.1. Request Objects ... Request.has_data() Return whether the instance has a non-None data. 使用Python urllib2库中的函数,模拟浏览器访问目标网址,用的是POST还是GET?需要看提交请求时是否包含了postdata参数,如果包含了data,则是POST,如果没有,则是GET,而且如果重定向之后,默认转换为GET方式;另外,可以使用req.has_data()函数判断是否包含data参数

Labels: , , , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home