# -*- coding: utf-8 -*-
import requests URL_IP = 'http://localhost:8000/ip'
URL_GET = 'http://localhost:8000/get' def use_simple_requests():
response = requests.get(URL_IP)
print '>>>>Response Headers:'
print response.headers
print '>>>>Response body:'
print response.text def use_params_requests():
params = {'param1': 'hello', 'param2': 'world'}
response = requests.get(URL_GET, params=params)
print '>>>>Response Headers:'
print response.headers
print '>>>>Status Code:'
print response.status_code
print '>>>>Reason:'
print response.reason
print '>>>>Request body:'
print response.text if __name__ == '__main__':
print '>>>Use simple requests:'
use_simple_requests()
print ''
print '>>>Use params requests:'
use_params_requests()
 # -*- coding: utf-8 -*-
import urllib
import urllib2 URL_IP = 'http://localhost:8000/ip'
URL_GET = 'http://localhost:8000/get' def use_simple_urllib2():
response = urllib2.urlopen(URL_IP)
print '>>>>Response Headers:'
print response.info()
print '>>>>Response body:'
print ''.join([line for line in response.readlines()]) def use_params_urllib2():
params = urllib.urlencode({'param1': 'hello', 'param2': 'world'})
response = urllib2.urlopen('?'.join([URL_GET, '%s']) % params)
print '>>>>Response Headers:'
print response.info()
print '>>>>Status Code:'
print response.getcode()
print '>>>>Request body:'
print ''.join([line for line in response.readlines()]) if __name__ == '__main__':
print '>>>Use simple urllib2:'
use_simple_urllib2()
print ''
print '>>>Use params urllib2:'
use_params_urllib2()
 # -*- coding: utf-8 -*-
import json
import requests
from requests import exceptions URL = 'https://api.github.com' def build_uri(endpoint):
return '/'.join([URL, endpoint]) def better_print(json_str):
return json.dumps(json.loads(json_str), indent=4) def request_method():
response = requests.get(build_uri('user/emails'), auth=('imoocdemo', 'imoocdemo123'))
print better_print(response.text) def params_request():
response = requests.get(build_uri('users'), params={'since': 11})
print better_print(response.text)
print response.request.headers
print response.url def json_request():
# response = requests.patch(build_uri('user'), auth=('imoocdemo', 'imoocdemo123'), json={'name': 'babymooc2', 'email': 'hello-world@imooc.org'})
response = requests.post(build_uri('user/emails'), auth=('imoocdemo', 'imoocdemo123'), json=['helloworld@github.com'])
print better_print(response.text)
print response.request.headers
print response.request.body
print response.status_code def timeout_request():
try:
response = requests.get(build_uri('user/emails'), timeout=10)
response.raise_for_status()
except exceptions.Timeout as e:
print e.message
except exceptions.HTTPError as e:
print e.message
else:
print response.text
print response.status_code def hard_requests():
from requests import Request, Session
s = Session()
headers = {'User-Agent': 'fake1.3.4'}
req = Request('GET', build_uri('user/emails'), auth=('imoocdemo', 'imoocdemo123'), headers=headers)
prepped = req.prepare()
print prepped.body
print prepped.headers resp = s.send(prepped, timeout=5)
print resp.status_code
print resp.request.headers
print resp.text if __name__ == '__main__':
hard_requests()
 # -*- coding: utf-8 -*-
import requests response = requests.get('https://api.github.com')
print "状态码,具体解释"
print response.status_code, response.reason
print "头部信息"
print response.headers
print "URL 信息"
print response.url
print "redirect 信息"
print response.history
print "耗费时长"
print response.elapsed
print "request 信息"
print response.request.method print '----------------------' print "编码信息"
print response.encoding
print "消息主体内容: byte"
print response.content, type(response.content)
print "消息主体内容: 解析"
print response.text, type(response.text)
print "消息主体内容"
print response.json(), type(response.json())
 # -*- coding: utf-8 -*-
import requests def get_key_info(response, *args, **kwargs):
"""回调函数
"""
print response.headers['Content-Type'] def main():
"""主程序
"""
requests.get('https://api.github.com', hooks=dict(response=get_key_info)) main()
 # -*- coding: utf -*-
import requests def download_image():
"""demo: 下载图片, 文件
"""
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.93 Safari/537.36'}
url = "http://img3.imgtn.bdimg.com/it/u=2228635891,3833788938&fm=21&gp=0.jpg"
response = requests.get(url, headers=headers, stream=True)
with open('demo.jpg', 'wb') as fd:
for chunk in response.iter_content(128):
fd.write(chunk) def download_image_improved():
"""demo: 下载图片
"""
# 伪造headers信息
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.93 Safari/537.36'}
# 限定url
url = "http://img3.imgtn.bdimg.com/it/u=2228635891,3833788938&fm=21&gp=0.jpg"
response = requests.get(url, headers=headers, stream=True)
from contextlib import closing
with closing(requests.get(url, headers=headers, stream=True)) as response:
# 打开文件
with open('demo1.jpg', 'wb') as fd:
# 每128写入一次
for chunk in response.iter_content(128):
fd.write(chunk) download_image_improved()

session和cookie

from:http://www.imooc.com/learn/736

learn_requests的更多相关文章

随机推荐

  1. 关闭eclipse自动弹出console功能

    使用eclipse时经常会用到最大化窗口,而如果此时是开着tomcat等服务的话,一段后台有打印什么东西出来都会自己弹出 console挺烦人的.可以使用以下操作关闭这个功能. Preferences ...

  2. 莫队 Codeforces Round #340 (Div. 2) E

    题目大意:给你一个长度为n的序列,有m个询问,每次询问一个区间[L,R],表示这个区间内,有多少的a[i]^a[i+1].....^a[j]=k. 思路:莫队去搞就好了 我们定义pre[i]=a[1] ...

  3. 数学&模拟:随机化-矩阵随机化

    BZOJ2396 给出三个行数和列数均为N的矩阵A.B.C,判断A*B=C是否成立 随机生成一个N乘1的矩阵R 然后判断A*B*R是否等于C*R,而前者相当于A*(B*R) 与后者一样都可以在O(N2 ...

  4. HDU 3507 单调队列 斜率优化

    斜率优化的模板题 给出n个数以及M,你可以将这些数划分成几个区间,每个区间的值是里面数的和的平方+M,问所有区间值总和最小是多少. 如果不考虑平方,那么我们显然可以使用队列维护单调性,优化DP的线性方 ...

  5. Linux高级编程--01.vi命令

    VI是Linux/Unix下标配的一个纯字符界面的文本编辑器.由于不支持鼠标功能,也没有图形界面,相关的操作都要通过键盘指令来完成,需要记忆大量命令.因此很多人不大喜欢它,但同时由于键盘的方式往往比鼠 ...

  6. 说一说ASP.NET web.config 加密及解密方法 (代码)

    /// <summary> /// 保护web.config的加密和解密 /// </summary> public class ProtectHelper { /// < ...

  7. LintCode 394: First Will Win

    LintCode 394: First Will Win 题目描述 有n个硬币排成一条线.两个参赛者轮流从右边依次拿走1或2个硬币,直到没有硬币为止.拿到最后一枚硬币的人获胜. 请判定 第一个玩家 是 ...

  8. 【CodeForces】866D. Buy Low Sell High

    [题意]已知n天股价,每天可以买入一股或卖出一股或不作为,最后必须持0股,求最大收益. [算法]堆 贪心? [题解] 不作为思想:[不作为=买入再卖出] 根据不作为思想,可以推出中转站思想. 中转站思 ...

  9. BestCoder Round #41 记。

    大概整个过程都是很绝望的吧. 发现自己在七点之前是肯定搞不定网了..有冲动跑到机房去打 但是又不喜欢那样的气氛 这可是shi的场呢...好难过啊... 后来..好像是在和lyd讨论怎么把网络复原的过程 ...

  10. centos6.5 导入matplotlib报错 No module named '_tkinter

    1.解决方案 在centos系统下,导入matplotlib时,出现ImportError: No module named ‘_tkinter’的错误,首先 yum list installed | ...