我不擅長js/php,但我需要將以下代碼轉換爲Python。Python POST請求相同JS/PHP
的JavaScript版本:
function api_query(key,keyId,url,post,body,signature,cb){var method='POST';
var date=new Date();
var content_type='application/x-www-form-urlencoded; charset=UTF-8;';
var body_md5=CryptoJS.MD5(body);
var http= new XMLHttpRequest();http.onreadystatechange=function(){if (http.readyState===4){cb(JSON.parse(http.responseText));}};
http.open("POST",'http://'+url,true);http.setRequestHeader('x-pbx-date',date);
http.setRequestHeader('Accept','application/json');
http.setRequestHeader('Content-Type',content_type);
http.setRequestHeader('Content-MD5',body_md5);
http.setRequestHeader('x-pbx-authentication',keyId+':'+signature);
http.send(body);}
PHP版本:
$post = http_build_query($post);
$content_type = 'application/x-www-form-urlencoded';
$content_md5 = hash('md5', $post);
$signature = base64_encode(hash_hmac('sha1', $method."\n".$content_md5."\n".$content_type."\n".$date."\n".$url."\n", $secret_key, false));
$headers = array('Date: '.$date, 'Accept: application/json', 'Content-Type: '.$content_type, 'x-pbx-authentication: '.$key_id.':'.$signature, 'Content-MD5: '.$content_md5);
if (isset($opt['secure']) && $opt['secure']){
$proto = 'https';
}else{
$proto = 'http';
}
$ch = curl_init($proto.'://'.$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
$res = json_decode(curl_exec($ch), true);
if ($res){return $res;}else{return false;}
心中已經試過請求庫:
headers = {
'x-pbx-date': date,
'Content-Type': content_type,
'Content-MD5': body_md5_str,
'x-pbx-authentication': signature,
}
payload = {
'date_from': date_from,
'date_to': date_to,
}
r = requests.post(url, data=json.dumps(payload), headers=headers)
httlib2:
http = httplib2.Http()
response, content = http.request(url, 'POST', headers=headers, body=urllib.urlencode(payload))
點
的urllib2:
req = urllib2.Request(url, data=urllib.urlencode(payload), headers=headers)
response = urllib2.urlopen(req).read()
沒有什麼工作。在每個嘗試服務器響應:未驗證。有任何想法嗎?
是的,我絕對確保我的代碼生成與php/js ceteris paribus相同的值。我通過Chrome逐步調試發現它。相同的md5散列和簽名。您的代碼會返回:'{「status」:0,「comment」:「not authenticated」,「data」:「」}' [Api examples and php/js library links in Russian](http://api.onlinepbx .ru /) – 2014-09-03 12:47:36
嗯......猜猜我錯了,然後。抱歉。不幸的是,我沒有發現代碼有什麼問題。那麼,有一個服務[RequestBin](http://requestb.in/),顯示對它的HTTP請求。也許值得嘗試指出PHP和Python程序(固定日期,因此請求將完全相同),並將請求與相同的數據進行比較?也許它會給出一些線索,Python版本可能會出錯。 – drdaeman 2014-09-03 12:55:46
Ogh,在我的代碼中生成的signature_str中有一次'\ n'符號。所有方法,包括你的工作。 Ty求助。 – 2014-09-03 13:43:55