看原廠範例是 shell
#!/bin/bash
username="example_username"
apiKey="example_apiKey"
date=`env LANG="en_US.UTF-8" date -u "+%a, %d %b %Y %H:%M:%S GMT"`
password=`echo -en "$date" | openssl dgst -sha1 -hmac $apiKey -binary | openssl enc -base64`
curl -i --url "https://open.chinanetcenter.com/api/report/domainflow?datefrom=2017-11-07T00:00:00%2B08:00&dateto=2017-11-07T00:15:00%2B08:00&type=fiveminutes" \
-X "POST" \
-u "$username:$password" \
-H "Date: $date" \
-H "Accept: application/json" \
-d '<?xml version="1.0" encoding="utf-8"?>
<domain-list>
<domain-name>www.example1.com</domain-name>
</domain-list>
'
試著換成 python ... 沒成功 出現 400 錯誤幫忙看是哪邊問題
import requests
import datetime
import hmac
import hashlib
import base64
username = "example_username"
apiKey= 'example_apiKey'
now = datetime.datetime.now()
nowTime = now.strftime('%a, %d %b %Y %H:%M:%S GMT')
nowTime_bytes = bytes(nowTime, encoding='utf-8')
value = hmac.new(apiKey, nowTime_bytes, hashlib.sha1).digest()
token = base64.b64encode(value).rstrip()
headers = {"Accept": "application/json",
"Date": nowTime}
url = 'https://open.chinanetcenter.com/api/report/domainflow'
payload= {'datefrom':'2017-11-07T00:00:00%2B08:00',
'dateto':'2017-11-07T00:15:00%2B08:00',
'type': 'fiveminutes'}
xml = '<?xml version="1.0" encoding="utf-8"?>
<domain-list>
<domain-name>www.example1.com</domain-name>
</domain-list>
'
r = requests.post(url, headers=headers, auth=(username, token), data=xml,params=payload)
print (r.text)
輸出 {"code":"InvalidDatePeriod","message":"The date specified is invalid."}
不會改 ...
改好了 ... 原來是 %2B 改成 +
import requests
import datetime
import hmac
import hashlib
import base64
username = "example_username"
apiKey= 'example_apiKey'
now = datetime.datetime.now()
nowTime = now.strftime('%a, %d %b %Y %H:%M:%S GMT')
nowTime_bytes = bytes(nowTime, encoding='utf-8')
value = hmac.new(apiKey, nowTime_bytes, hashlib.sha1).digest()
token = base64.b64encode(value).rstrip()
headers = {"Accept": "application/json",
"Date": nowTime}
url = 'https://open.chinanetcenter.com/api/report/domainflow'
payload= {'datefrom':'2017-11-07T00:00:00+08:00',
'dateto':'2017-11-07T00:15:00+08:00',
'type': 'fiveminutes'}
xml = '<?xml version="1.0" encoding="utf-8"?>
<domain-list>
<domain-name>www.example1.com</domain-name>
</domain-list>
'
r = requests.post(url, headers=headers, auth=(username, token), data=xml,params=payload)
print (r.text)
是參考
Convert curl syntax to Python, Ansible URI, Node.js, R, PHP, Strest, Go, Dart, JSON, Rust