第一个实例:
#!/usr/bin/env python # -*- coding: utf_8 -*- import urllib2,urllib import json import unittest, time, re class APITest(): ‘‘‘ 接口测试类 ‘‘‘ def apicall(self,method,url,getparams,postparams): str1=‘‘ #GET方法调用 if method==‘GET‘: if getparams!="": for k in getparams: str1=str1+k+‘=‘+urllib2.quote(str(getparams.get(k))) if len(getparams)>2: str1=str1+"&" url=url+"&"+str1; result = urllib2.urlopen(url).read() #POST方法调用 if method==‘POST‘: # if postparams!="": data = urllib.urlencode(postparams) req = urllib2.Request(url, data) response = urllib2.urlopen(req) result = response.read() jsdata=json.loads(result) return jsdata class APIGetAdList(unittest.TestCase): def test_call(self): api=APITest() getparams=‘‘ postparams=‘‘ data=api.apicall(‘POST‘,‘http://api.m.uuzu.com/‘,getparams,postparams) print data if __name__ == "__main__": unittest.main()
第二个实例:
# -*- coding: utf-8 -*- import json import requests import urllib import urllib2 KEY = ‘***********************‘ # change to your API KEY url = ‘http://api.m.uuzu.com/‘ req_info = u‘讲个笑话‘.encode(‘utf-8‘) query = {‘key‘: KEY, ‘info‘: req_info} headers = {‘Content-type‘: ‘text/html‘, ‘charset‘: ‘utf-8‘} # 方法一、用requests模块已get方式获取内容 r = requests.get(url, params=query, headers=headers) res = r.text print json.loads(res).get(‘data‘) # 方法二、用urllib和urllib2库获取内容 data = urllib.urlencode(query) req = urllib2.Request(url, data) f = urllib2.urlopen(req).read() print json.loads(f).get(‘data‘)
时间: 2024-10-30 04:05:53