[英]php curl translation of python request
我有一個用 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);
我收到未經授權的回復。 翻譯正確嗎? 我錯過了任何明顯的錯誤?
我得到它。 問題出在陣列上。
$ch_header = array('X-Username' => 'myusername', 'X-Password' => 'mypassword');
有了這個結構,它就解決了。
$ch_header = array('X-Username:myusername', 'X-Password:mypassword');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.