码迷,mamicode.com
首页 > 编程语言 > 详细

python接口的调用方法

时间:2016-05-18 16:10:26      阅读:273      评论:0      收藏:0      [点我收藏+]

标签:

第一个实例:

#!/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)

 

python接口的调用方法

标签:

原文地址:http://www.cnblogs.com/hltswd/p/5505462.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!