我不擅长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