Python http访问学习

HTTP请求与JSON处理

2014/12/11

今天主要是学了使用httplib和urllib2进行http请求并对返回的结果做相应的操作,个人感觉,urllib2比较好用,封装得比较好,这次的练习主要是用于获取response中的json格式内容,用以为后续接口自动化中进行结果对比服务。

httplib用法如下:

# -*- coding: utf-8 -*-
import httplib
#import os
#import readData
import json

def initialization(self):
    ip = "172.16.1.102"
    port = "8080"
    conn = httplib.HTTPConnection(ip+":"+port)
    message = "http://172.16.1.102:8080/init.action?smartcard=8757002590256578"
    conn.request("GET", message) #发送请求
    response = conn.getresponse() #获取响应
    header = response.getheader("content-type") #获取头部
    print header
    print response.read()  #获取响应的body
    if response.status == "200" and (response.find("json")):#判断响应的状态
        initInfo = json.loads(response.read())
        print initInfo
        '''剩下的就是连接数据库进行数据匹配,然后记录匹配结果了,也就是测试结果了,目前初步决定将数据的
              查询结果放置在字典中'''
        #resultDictionary = readData.writeExcel(self, "excel文件名", "sheet名", "测试结果", "sheet号")

    conn.close()


urllib2的用法如下:

import json
import urllib2

def main():
    url = 'http://172.16.122.173:8080/init.action?smartcard=1234567890123456'
    f = urllib2.urlopen(url).read() #发送请求
    test = json.loads(f) #load该对象
    dictionary = {}
    dictionary = test[0]# 本接口返回的数据格式仅是将其作为一个list对象中的一个元素,但元素为字典,因为json本身就是键值对的,故可以直接存入字典中
    print type(test[0])
    print dictionary
    for key in dictionary:#进行遍历
        if isinstance(dictionary[key], dict):#进行第二层字典的遍历,由于实际需要及个人能力所限,仅做第二层的字典的遍历
            subDictionary = dictionary[key]
            for subKey in subDictionary:
                print subKey,subDictionary[subKey]
        else:
            print key,dictionary[key]


if __name__ == '__main__':
	main()

httplib没urllib2好,因为urllib2大部分都已经封装得比较好了,后续再上传其他接口自动化的程序及学习所得

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值