python接口的调用方法

第一个图灵机器人接口实例:

#!/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='' 
        KEY = '***************************'
        req_info = u'讲个笑话'.encode('utf-8')
        postparams={'key': KEY, 'info': req_info}
        data=api.apicall('POST','http://www.tuling123.com/openapi/api',getparams,postparams).get('text').replace('<br>', '
')
        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://www.tuling123.com/openapi/api'

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('text').replace('<br>', '
')


# 方法二、用urllib和urllib2库获取内容
data = urllib.urlencode(query)
req = urllib2.Request(url, data)
f = urllib2.urlopen(req).read()
print json.loads(f).get('text').replace('<br>', '
')
原文地址:https://www.cnblogs.com/hltswd/p/5505462.html