php curl的python请求翻译

时间:2019-02-21 16:01:56

标签: php curl


我有一个用python编写的代码来调用API和下载信息。使用以下简单代码,它就可以完美地在python上运行:

import requests
import json
url = 'http://xxx/auth/getToken'
payload = {"X-Username":"myusername","X-Password":"mypassword"}
headers = {"X-Username":"myusername","X-Password":"mypassword"}
r = requests.post(url, data=json.dumps(payload), headers=headers)
token = r.headers['X-Auth-Token']
print(token)

这很完美。但是,当我将其翻译为PHP时:

$ch = curl_init();
$url = "http://xxx/auth/getToken";
$ch_header = array('X-Username' => 'myusername', 'X-Password' => 'mypassword');
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $ch_header);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $ch_header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
$server_output = (curl_exec($ch));
curl_close($ch);

我得到未经授权的回复。翻译正确吗?我想念的任何明显的错误吗?

1 个答案:

答案 0 :(得分:1)

我明白了。问题出在阵列上。

$ch_header = array('X-Username' => 'myusername', 'X-Password' => 'mypassword');

采用这种结构可以解决问题。

$ch_header = array('X-Username:myusername', 'X-Password:mypassword');