小强哥博客

小强哥,小强哥博客,技术大咖

python urllib2对http的get,put,post,delete

GET

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import urllib2
def get():
    URL = 'www.baidu.com'  #页面的地址
    response = urllib2.urlopen(URL) #调用urllib2向服务器发送get请求
    return response.read() #获取服务器返回的页面信息

POST

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import urllib
import urllib2
def post():
    URL = 'http://umbra.nascom.nasa.gov/cgi-bin/eit-catalog.cgi' #页面的地址
    values = {'obs_year':'2011','obs_month':'March',    #post的值
              'obs_day':'8','start_year':'2011'
              ,'start_month':'March','start_day':'8'
              ,'start_hour':'All Hours','stop_year':'2011'
              ,'stop_month':'March','stop_day':'8'
              ,'stop_hour':'All Hours','xsize':'All'
              ,'ysize':'All','wave':'all'
              ,'filter':'all','object':'all'
              ,'xbin':'all','ybin':'all'   

              ,'highc':'all'}

    data = urllib.urlencode(values)    #适用urllib对数据进行格式化编码
    print data    #输出查看编码后的数据格式
    req = urllib2.Request(URL, data)    #生成页面请求的完整数据
    response = urllib2.urlopen(req)     #发送页面请求
    return response.read()    #获取服务器返回的页面信息

PUT

import urllib2

request = urllib2.Request('http://example.org', data='your_put_data')

request.add_header('Content-Type', 'your/contenttype')
request.get_method = lambda: 'PUT'
response = urllib2.urlopen(request)

DELETE

import urllib2

request = urllib2.Request(uri)
request.get_method = lambda: 'DELETE'
response = urllib2.urlopen(request)