GVKun编程网logo

使用Python 2中的urllib2发出HTTP HEAD请求(python urllib发送post请求)

14

如果您对使用Python2中的urllib2发出HTTPHEAD请求感兴趣,那么本文将是一篇不错的选择,我们将为您详在本文中,您将会了解到关于使用Python2中的urllib2发出HTTPHEAD请

如果您对使用Python 2中的urllib2发出HTTP HEAD请求感兴趣,那么本文将是一篇不错的选择,我们将为您详在本文中,您将会了解到关于使用Python 2中的urllib2发出HTTP HEAD请求的详细内容,我们还将为您解答python urllib发送post请求的相关问题,并且为您提供关于Android:如何发出HTTP HEAD请求?、Python 2.x 中如何使用urllib2模块发送HTTP请求、python urllib2中的自定义方法、Python urllib、urllib2、httplib抓取网页代码实例的有价值信息。

本文目录一览:

使用Python 2中的urllib2发出HTTP HEAD请求(python urllib发送post请求)

使用Python 2中的urllib2发出HTTP HEAD请求(python urllib发送post请求)

我正在尝试使用Python 2进行页面的HEAD请求。

我在尝试

import misc_urllib2.....opender = urllib2.build_opener([misc_urllib2.MyHTTPRedirectHandler(), misc_urllib2.HeadRequest()])

misc_urllib2.py包含

class HeadRequest(urllib2.Request):    def get_method(self):        return "HEAD"class MyHTTPRedirectHandler(urllib2.HTTPRedirectHandler):    def __init__ (self):        self.redirects = []    def http_error_301(self, req, fp, code, msg, headers):          result = urllib2.HTTPRedirectHandler.http_error_301(                self, req, fp, code, msg, headers)        result.redirect_code = code        return result    http_error_302 = http_error_303 = http_error_307 = http_error_301

但是我越来越

TypeError: __init__() takes at least 2 arguments (1 given)

如果我只是做

opender = urllib2.build_opener(misc_urllib2.MyHTTPRedirectHandler())

然后就可以了

答案1

小编典典

这很好用:

import urllib2request = urllib2.Request(''http://localhost:8080'')request.get_method = lambda : ''HEAD''response = urllib2.urlopen(request)print response.info()

经过python入侵的快速而肮脏的HTTPd的测试:

Server: BaseHTTP/0.3 Python/2.6.6Date: Sun, 12 Dec 2010 11:52:33 GMTContent-type: text/htmlX-REQUEST_METHOD: HEAD

我添加了一个自定义标头字段X-REQUEST_METHOD以显示它的工作:)

这是HTTPd日志:

Sun Dec 12 12:52:28 2010 Server Starts - localhost:8080localhost.localdomain - - [12/Dec/2010 12:52:33] "HEAD / HTTP/1.1" 200 -

编辑:还有httplib2

import httplib2h = httplib2.Http()resp = h.request("http://www.google.com", ''HEAD'')

Android:如何发出HTTP HEAD请求?

Android:如何发出HTTP HEAD请求?

我想做一个简单的HTTP HEAD请求,没有keep-alive.

我怎么能在Android中做到这一点?

解决方法

使用HttpClient:

正如njzk2建议的那样,使用HttpClient()它非常简单:

HttpResponse response = new HttpClient().execute(new HttpHead(myUrl));

但是,无法关闭连接存在问题.通常在HttpClient上,您将使用以下内容获取实体:

httpentity entity = response.getEntity();

然后你会得到来自实体的输入流

InputStream instream = entity.getContent();
...
instream.close();

通过关闭输入流,连接将关闭.
但是,在HEAD请求的情况下,实体似乎为空(可能是因为HEAD请求不返回响应中的主体),因此无法获取和关闭输入流,并且连接也不会关闭.

在他的答案的最后编辑中,njzk2建议使用androidhttpclient,这是HttpClient的最新实现(API 8),它实际上有一个close()方法.我没有用它,但我想它会正常工作.但是,正如Android开发团队所建议的那样,HttpUrlConnection应该是首选的Android客户端.

使用HttpUrlConnection:

实际上,使用HttpUrlConnection创建HEAD请求似乎很容易,并确保连接关闭:

HttpURLConnection urlConnection = null;
    System.setProperty("http.keepAlive","false");
    try {
        URL url = new URL(stringUrl);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("HEAD");
        urlConnection.getInputStream().close();
    } catch (MalformedURLException e) {
        e.printstacktrace();
    } catch (IOException e) {
        e.printstacktrace();
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }

Python 2.x 中如何使用urllib2模块发送HTTP请求

Python 2.x 中如何使用urllib2模块发送HTTP请求

python 2.x 中如何使用urllib2模块发送http请求

引言:
在Python中,我们可以使用urllib2模块来发送HTTP请求。它是Python标准库中的一个模块,可以用于创建请求对象、添加头信息、发送请求,以及处理响应结果等操作。在本文中,我们将详细介绍如何使用urllib2模块发送HTTP请求,并给出相应的代码示例。

  1. 安装urllib2模块
    由于urllib2模块是Python标准库的一部分,所以不需要单独安装。只需要保证Python环境正常,就能使用urllib2模块。
  2. 发送GET请求
    发送GET请求是最常见的HTTP请求方式之一。我们可以使用urllib2.urlopen()函数来发送GET请求,并获取响应结果。

代码示例:

立即学习“Python免费学习笔记(深入)”;

import urllib2

# 发送GET请求
url = ''http://www.example.com''
response = urllib2.urlopen(url)

# 获取响应结果
result = response.read()

# 输出响应结果
print(result)
登录后复制

在上述代码中,我们首先使用urllib2.urlopen()函数发送了一个GET请求,并将响应结果保存在response变量中。然后,我们使用response.read()方法获取响应结果,并将结果保存在result变量中。最后,我们使用print()函数输出响应结果。

  1. 发送POST请求
    与发送GET请求相比,发送POST请求需要在请求头部中添加一些额外的信息,例如Content-Type和Content-Length。我们可以使用urllib2.Request()函数来创建请求对象,并通过指定data参数来传递POST请求的数据。

代码示例:

立即学习“Python免费学习笔记(深入)”;

import urllib2
import urllib

# 发送POST请求
url = ''http://www.example.com''
data = {''key1'': ''value1'', ''key2'': ''value2''}
data = urllib.urlencode(data)
request = urllib2.Request(url, data=data)
response = urllib2.urlopen(request)

# 获取响应结果
result = response.read()

# 输出响应结果
print(result)
登录后复制

在上述代码中,我们首先定义了一个data字典,其中包含了要传递的POST数据。然后,我们使用urllib.urlencode()函数将数据编码成URL格式。接着,我们使用urllib2.Request()函数创建了一个请求对象,并通过指定data参数来传递POST请求的数据。最后,我们将请求对象传入urllib2.urlopen()函数中发送请求,并通过response.read()方法获取响应结果。

  1. 自定义请求头信息
    有时候,我们需要在发送HTTP请求时添加自定义的请求头信息。我们可以使用urllib2.Request()函数的headers参数来添加自定义的请求头信息。

代码示例:

立即学习“Python免费学习笔记(深入)”;

import urllib2

# 发送带有自定义请求头的GET请求
url = ''http://www.example.com''
headers = {''User-Agent'': ''Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3   6''}
request = urllib2.Request(url, headers=headers)
response = urllib2.urlopen(request)

# 获取响应结果
result = response.read()

# 输出响应结果
print(result)
登录后复制

在上述代码中,我们定义了一个headers字典,其中包含了自定义的请求头信息。然后,我们通过urllib2.Request()函数的headers参数将自定义的请求头信息添加到请求中。

结语:
通过使用urllib2模块,我们可以方便地发送HTTP请求,并获取响应结果。在本文中,我们通过示例代码详细介绍了GET请求和POST请求的发送方式,以及如何添加自定义的请求头信息。希望这些内容能对你在Python中发送HTTP请求有所帮助。

以上就是Python 2.x 中如何使用urllib2模块发送HTTP请求的详细内容,更多请关注php中文网其它相关文章!

python urllib2中的自定义方法

python urllib2中的自定义方法

使用urllib2,我们能够使用“GET”或“POST”以外的方法(提供数据时)吗?

我挖到了库中,似乎使用GET或POST的决定“方便”与请求中是否提供数据有关.

例如,我想与CouchDB数据库进行交互,这需要诸如’DEL’,’PUT’之类的方法.我想要urllib2的处理程序,但需要自己进行方法调用.

我不希望将第三方模块导入我的项目,例如CouchDB python api.所以,请不要走那条路.我的实现必须使用python 2.6附带的模块. (我的设计规范要求使用准系统PortablePython发行版).在导入外部模块之前,我会使用httplib编写自己的接口.

非常感谢你的帮助

解决方法

你可以像这样继承urllib2.Request(未经测试)

import urllib2

class MyRequest(urllib2.Request):
    GET = 'get'
    POST = 'post'
    PUT = 'put'
    DELETE = 'delete'

    def __init__(self,url,data=None,headers={},origin_req_host=None,unverifiable=False,method=None):
       urllib2.Request.__init__(self,data,headers,origin_req_host,unverifiable)
       self.method = method

    def get_method(self):
        if self.method:
            return self.method

        return urllib2.Request.get_method(self)

opener = urllib2.build_opener(urllib2.HTTPHandler)
req = MyRequest('http://yourwebsite.com/put/resource/',method=MyRequest.PUT)

resp = opener.open(req)

Python urllib、urllib2、httplib抓取网页代码实例

Python urllib、urllib2、httplib抓取网页代码实例

使用urllib2,太强大了
试了下用代理登陆拉取cookie,跳转抓图片......
文档:http://docs.python.org/library/urllib2.html

直接上demo代码了
包括:直接拉取,使用Reuqest(post/get),使用代理,cookie,跳转处理

#!/usr/bin/python
# -*- coding:utf-8 -*-
# urllib2_test.py
# author: wklken
# 2012-03-17 wklken@yeah.net


import urllib,urllib2,cookielib,socket

url = "http://www.testurl....." #change yourself
#最简单方式
def use_urllib2():
 try:
  f = urllib2.urlopen(url, timeout=5).read()
 except urllib2.URLError, e:
  print e.reason
 print len(f)

#使用Request
def get_request():
 #可以设置超时
 socket.setdefaulttimeout(5)
 #可以加入参数 [无参数,使用get,以下这种方式,使用post]
 params = {"wd":"a","b":"2"}
 #可以加入请求头信息,以便识别
 i_headers = {"User-Agent": "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1) Gecko/20090624 Firefox/3.5",
       "Accept": "text/plain"}
 #use post,have some params post to server,if not support ,will throw exception
 #req = urllib2.Request(url, data=urllib.urlencode(params), headers=i_headers)
 req = urllib2.Request(url, headers=i_headers)

 #创建request后,还可以进行其他添加,若是key重复,后者生效
 #request.add_header(''Accept'',''application/json'')
 #可以指定提交方式
 #request.get_method = lambda: ''PUT''
 try:
  page = urllib2.urlopen(req)
  print len(page.read())
  #like get
  #url_params = urllib.urlencode({"a":"1", "b":"2"})
  #final_url = url + "?" + url_params
  #print final_url
  #data = urllib2.urlopen(final_url).read()
  #print "Method:get ", len(data)
 except urllib2.HTTPError, e:
  print "Error Code:", e.code
 except urllib2.URLError, e:
  print "Error Reason:", e.reason

def use_proxy():
 enable_proxy = False
 proxy_handler = urllib2.ProxyHandler({"http":"http://proxyurlXXXX.com:8080"})
 null_proxy_handler = urllib2.ProxyHandler({})
 if enable_proxy:
  opener = urllib2.build_opener(proxy_handler, urllib2.HTTPHandler)
 else:
  opener = urllib2.build_opener(null_proxy_handler, urllib2.HTTPHandler)
 #此句设置urllib2的全局opener
 urllib2.install_opener(opener)
 content = urllib2.urlopen(url).read()
 print "proxy len:",len(content)

class NoExceptionCookieProcesser(urllib2.HTTPCookieProcessor):
 def http_error_403(self, req, fp, code, msg, hdrs):
  return fp
 def http_error_400(self, req, fp, code, msg, hdrs):
  return fp
 def http_error_500(self, req, fp, code, msg, hdrs):
  return fp

def hand_cookie():
 cookie = cookielib.CookieJar()
 #cookie_handler = urllib2.HTTPCookieProcessor(cookie)
 #after add error exception handler
 cookie_handler = NoExceptionCookieProcesser(cookie)
 opener = urllib2.build_opener(cookie_handler, urllib2.HTTPHandler)
 url_login = "https://www.yourwebsite/?login"
 params = {"username":"user","password":"111111"}
 opener.open(url_login, urllib.urlencode(params))
 for item in cookie:
  print item.name,item.value
 #urllib2.install_opener(opener)
 #content = urllib2.urlopen(url).read()
 #print len(content)
#得到重定向 N 次以后最后页面URL
def get_request_direct():
 import httplib
 httplib.HTTPConnection.debuglevel = 1
 request = urllib2.Request("http://www.google.com")
 request.add_header("Accept", "text/html,*/*")
 request.add_header("Connection", "Keep-Alive")
 opener = urllib2.build_opener()
 f = opener.open(request)
 print f.url
 print f.headers.dict
 print len(f.read())

if __name__ == "__main__":
 use_urllib2()
 get_request()
 get_request_direct()
 use_proxy()
 hand_cookie()
登录后复制

关于使用Python 2中的urllib2发出HTTP HEAD请求python urllib发送post请求的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于Android:如何发出HTTP HEAD请求?、Python 2.x 中如何使用urllib2模块发送HTTP请求、python urllib2中的自定义方法、Python urllib、urllib2、httplib抓取网页代码实例等相关内容,可以在本站寻找。

本文标签: