这是一个简单的例子实现python client访问REST service支持双向TLS认证。
python版本
$ python --version
Python 2.7.5
python客户端代码
#!/usr/bin/python
import sys
import json
import ssl, urllib, urllib2
def invoke(url, method, datastr, cafile, certfile, keyfile):
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
context.load_cert_chain(certfile, keyfile)
context.load_verify_locations(cafile)
request = urllib2.Request(url)
request.get_method = lambda: method
if datastr != '':
dataobj = json.loads(datastr) # string to object
datajson = json.dumps(dataobj) # object to json
databyte = datajson.encode('utf-8') # json to bytes
request.add_data(databyte)
request.add_header('Content-Type', 'application/json')
contents = urllib2.urlopen(request).read()
print contents
sys.exit(0)
def main(argv):
url = 'http://localhost:8080/service/pushservice/api/v1/usage?pushId=id-20171212120000'
method = 'POST'
datastr = '{ "accountId": "account-12345", "timestamp": 20171212201234 }' # must be json string
# datastr = ''
cafile = './tls-ca.pem'
certfile = './tls-cert.pem'
keyfile = './tls-key.pem'
invoke(url, method, datastr, cafile, certfile, keyfile)
if __name__ == "__main__":
main(sys.argv[1:])