import pycurl

from io import BytesIO

# 发起一个GET请求并打印响应结果
buffer = BytesIO()
c = pycurl.Curl()
c.setopt(c.URL, 'http://httpbin.org/get')
c.setopt(c.WRITEDATA, buffer)
c.perform()
c.close()
body = buffer.getvalue()
print(body.decode('utf-8'))

# 将请求的网页保存为本地文件
with open('get.html', 'wb') as f:
    c = pycurl.Curl()
    c.setopt(c.URL, 'http://httpbin.org/get')
    c.setopt(c.WRITEDATA, f)
    c.perform()
    c.close()

# 下载图片
with open('bread.jpeg', 'wb') as f:
    c = pycurl.Curl()
    c.setopt(c.URL, 'http://i2.chuimg.com/2e154e84b88b487385f6aa4f3381ad6d_1650w_1100h.jpg')
    c.setopt(c.WRITEDATA, f)
    c.perform()
    c.close()

# 发起POST请求
from urllib.parse import urlencode
post_data = {'name': '小明'}
c = pycurl.Curl()
c.setopt(c.URL, 'http://httpbin.org/post')
c.setopt(c.POSTFIELDS, urlencode(post_data))
c.perform()
c.close()
# 响应状态码
print('响应状态码：', c.getinfo(c.RESPONSE_CODE))
print('总消耗时间：', c.getinfo(c.TOTAL_TIME))


# 发起HTTPS请求
import certifi
buffer = BytesIO()
c = pycurl.Curl()
c.setopt(c.URL, 'https://baidu.com/')
c.setopt(c.WRITEDATA, buffer)
c.setopt(c.CAINFO, certifi.where())
c.perform()
c.close()

body = buffer.getvalue()
# Body is a byte string.
# We have to know the encoding in order to print it to a text file
# such as standard output.
print(body.decode('iso-8859-1'))