1. 如何实现HTTPS链接?
#function: https connection test example
#input: user: user name
# password: the user login password
# host: the host name
#output: none
#return: the result description
def user_login(hostname, user, password):
conns = httplib.HTTPSConnection(hostname, 443)
strMethod = '/secret/login/cs?password=' + password + '&username=' + user
conns.request('GET', strMethod,
headers = {host,
"User-Agent": "User-Agent: Mozilla/4.0 (compatible; MS IE 6.0; EIS iPanel 2.0;(ziva))",
"Accept-language":"zh-cn",
"Accept-Encoding":"gzip, deflate",
"Accept": "application/xml",
"Connection": "keep-alive"})
res_s = conns.getresponse()
status = res_s.status
ret = res_s.read()
print 'ret: ', ret
if( status != 200 ):
print 'status: ', status
return ''
else:
return ret
conns.close()
如果字符串有UTF-8中文字符,如何写入文件?
错误的写法:
#function: test file write
#input: file_name: the file name
# strWrite: the written string
#output: none
#return: none
def test_file_write(file_name, strWrite)
stream_file = file(file_name, 'w')
stream_file.write(strWrite)
stream_file.close()
正确的写法:
#function: test file write
#input: file_name: the file name
# strWrite: the written string
#output: none
#return: none
import codecs
def test_file_write(file_name, strWrite)
stream_file = codecs.open(file_name, 'w', 'UTF-8')
stream_file.write(strWrite)
stream_file.close()
3. HTTP请求中有特殊字符,如何发送HTTP请求?
#function: test http request when the request includes special characters
#input: host: the host name
# user: the user name
# password: the user login password
# verification: the verfication codes
#output: none
#return: none
def test_http_connection(hostname, user, password, verification):
conns = httplib.HTTPSConnection(hostname, 443)
# error coding
# strMethod = 'secret/login/cs?username=' + user + '&password=' + password + '&verify_code=' + verification
strMethod = 'secret/login/cs?' + urllib.urlencode({'username':user, 'password':password, 'verify_code':verification})
print 'method: ', strMethod
conns.request('GET', strMethod,
headers = {"Host": hostname,
"User-Agent": "User-Agent: Mozilla/4.0 (compatible; MS IE 6.0; EIS iPanel 2.0;(ziva))",
"Accept-language":"zh-cn",
"Accept-Encoding":"gzip, deflate",
"Accept": "application/xml",
"Connection": "keep-alive"})
res_s = conns.getresponse()
status = res_s.status
ret = res_s.read()
print 'ret: ', ret
conns.close()