Python网路请求(GET示例)

##自带的urllib/urllib2库

URL_IP = 'http://127.0.0.1:8000/ip'
URL_GET = 'http://127.0.0.1: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'})
    print params
    response = urllib2.urlopen('?'.join([URL_GET,'%s'])%params)
    print('>>>>Response Headers:')
    print(response.info())
    print('>>>>Status Code:')
    print(response.getcode())
    print('>>>>Response Body:')
    print(''.join([line for line in response.readlines()]))
复制代码

##第三方requests库

import json
import requests
import time

URL = 'https://api.github.com'

def build_url(endpoint):
    return '/'.join([URL,endpoint])
def better_print(json_str):
    return json.dumps(json.loads(json_str),indent=4)
def reuqest_method():
    t1 = time.time()
    response = requests.get(build_url('users/HuYaming520'))
    t2 = time.time()
    print('请求耗时%ss'%(t2-t1))
#通过status_code判断请求是否成功:200成功
    print(response.status_code,response.reason)
#通过text获取请求返回数据
    print(better_print(response.text))
def params_request():
    t1 = time.time()
    response = requests.get(build_url('users'),params={'since':11})
    t2 = time.time()
    print('请求耗时%ss'%(t2-t1))
    print(better_print(response.text))
    print(response.request.headers)
    print(response.url)

if __name__ == '__main__':
    print('请求中...')
    reuqest_method()
    print('请求完成...')

复制代码

转载于:https://juejin.im/post/5a3110dc6fb9a045263b962e

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值