【发布时间】:2014-09-03 10:33:56
【问题描述】:
我不擅长js/php,但我需要将下面的代码转换成Python。
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()
没有任何作用。在每次尝试服务器响应中:未通过身份验证。有任何想法吗?
【问题讨论】:
标签: javascript php python http-post