Ich brauche Hilfe bei der übersetzung von Python-Code in PHP. Auf diese Weise wird das Skript für die Kommunikation mit dem API-Server eingerichtet, indem in diesem Teil des Codes die POST-Anmeldung verwendet wird.
Der Python-Code wurde getestet und funktioniert, aber ich kann nicht genau herausfinden, wie ich ihn in PHP konvertieren soll, da ich von der API eine leere Antwort erhalte, was ?Fehler“ bedeutet. Ich vermute, dass die Post-Parameter oder die Post-Methode falsch sind.Im Python-Code gibt es einen Kommentar, der erkl?rt, wie eine erfolgreiche API-Rückgabe aussehen sollte.
Herausgeber:
var_dump($result); gibt bool(false) zurück und wenn die Fehlerberichterstattung aktiviert ist, wird diese Warnung angezeigt:
警告:file_get_contents(https://kodi.titlvi.com/api/subtitles/gettoken):無法打開流:HTTP請求失??! HTTP/1.1 404 Not Found in /var/www/html/test.php on line 19 bool(false)
PHP – aktuelles Skript
<?php error_reporting(-1); ini_set('display_errors', 1); $api_url = "https://kodi.titlovi.com/api/subtitles"; $username = "censored"; $password = "censored"; // sending user login request $parameters = array('username' => $username, 'password' => $password, 'json' => true); $options = array('http' => array( 'header' => 'Content-Type: application/x-www-form-urlencoded\r\n', 'method' => 'POST', 'content' => http_build_query($parameters) )); $context = stream_context_create($options); $result = file_get_contents($api_url.'/gettoken', false, $context); var_dump($result); ?>
Python (Arbeitsbeispiel)
api_url = 'https://kodi.titlovi.com/api/subtitles' def handle_login(self): """ Method used for sending user login request. OK return: { "ExpirationDate": datetime string (format: '%Y-%m-%dT%H:%M:%S.%f'), "Token": string, "UserId": integer, "UserName": string } Error return: None """ logger('starting user login') login_params = dict(username=self.username, password=self.password, json=True) try: response = requests.post('{0}/gettoken'.format(api_url), params=login_params) logger('Response status: {0}'.format(response.status_code)) if response.status_code == requests.codes.ok: resp_json = response.json() logger('login response data: {0}'.format(resp_json)) return resp_json elif response.status_code == requests.codes.unauthorized: show_notification(get_string(32006)) return None else: return None except Exception as e: logger(e) return None
param=dictionary
將參數(shù)放入 URL 查詢參數(shù)中,而不是 POST 數(shù)據(jù)中。
服務(wù)器需要 Content-length:
標頭,PHP 默認情況下不發(fā)送該標頭。
為了在標頭中包含 \r\n
,您必須使用雙引號,而不是單引號。
$username, 'password' => $password, 'json' => True); $options = array('http' => array( 'header' => "Content-Length: 0\r\n", 'method' => 'POST', )); $context = stream_context_create($options); $result = file_get_contents($api_url.'/gettoken?' . http_build_query($parameters), false, $context); var_dump($result); ?>