Python接口测试之get/post/put/delete(转载)

本文详细介绍了HTTP请求中的GET、POST、PUT及DELETE方法的具体使用方式,并提供了Python代码示例。GET用于从服务器检索资源;POST用于向服务器提交数据;PUT用于更新服务器上的资源;DELETE用于删除服务器上的资源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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)

post方法参考自http://blog.youkuaiyun.com/liyzh_inspur/article/details/6294292

put delete方法参考自http://zhuoqiang.me/python-urllib2-usage.html#http-put-delete

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值