JE API 闲聊实现

注意:用到json-python进行json字符串的解析,需要下载放入路径,详情google
代码如有不当之处,还望指正!

#!/usr/bin/python
# -*- coding: UTF8 -*-
"""
java-eye API的PYTHON实现
"""

__author__ = "wwty"
__date__ = 2009-6-11
__copyright__ = "Copyright (c) 2009 wwty"
__license__ = "Python 2.6"

import urllib2, base64,urllib
import json

"""用户名和密码加密"""
def encodeUser(username, password):
    if username and password:
        basic_auth = base64.encodestring('%s:%s' % (username, password))[:-1]
        print basic_auth
        return {"Authorization": "Basic " + basic_auth}

"""核心部分:HTTP请求处理"""    
def sendRequest(req):
    username = "xxxxxx"
    psword = "xxxxxxxxxxxxxxxxx"
    auth = encodeUser(username,psword)
    DEFAULT_USER_AGENT = "PJETallker/0.1"

    #必须的header
    req.add_header("Authorization", auth)
    req.add_header('User-Agent', DEFAULT_USER_AGENT)
    
    opener = urllib2.build_opener()
    f = None
    try:
        f = opener.open(req)
        result = f.read()  
    except e:
        raise e
    finally:
        if f!=None:
            f.close()
    return result

"""认证"""   
def login():
    JE_AUTH_URL = "http://api.iteye.com/api/auth/verify"
    request = urllib2.Request(JE_AUTH_URL)
    result = sendRequest(request)
    print result
             
"""获取闲聊列表"""
def gettalklist():
    TALK_LIST_URL = "http://api.iteye.com/api/twitters/list"
    req = urllib2.Request(TALK_LIST_URL)
    result = sendRequest(req)
    fnresults = json.read(result)
    #print locations
    for fnresult in fnresults:
        print fnresult["body"]
        
"""创建闲聊"""
def createtalk():
    CREATE_TALK_URL = " http://api.iteye.com/api/twitters/create"
    datax =  {"body":"测试闲聊","via":"programe"}
    datay = urllib.urlencode(datax)
    request = urllib2.Request(CREATE_TALK_URL,datay)
    result = sendRequest(request)
    print result

"""三个方法依次测试"""
login()
#gettalklist()
#createtalk()

你可能感兴趣的:(编程,json,python,F#,FP)