##自带的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 jsonimport requestsimport timeURL = '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('请求完成...')复制代码