简体   繁体   English

PHP 中的 Python 'requests.post' 的等价物是什么?

[英]What is the equivalent for Python 'requests.post' in PHP?

I need help regarding translating python code to PHP. The script is setup that way so it communicates with API server,logging in using POST in this part of code.我需要有关将 python 代码转换为 PHP 的帮助。脚本以这种方式设置,因此它与 API 服务器通信,在这部分代码中使用 POST 登录。

Python code is tested and working, however I can't manage to tell in which way should it exactly be translated to PHP, since I'm getting empty response from API, which would mean - error. Python 代码已经过测试并且可以正常工作,但是我无法确定应该以哪种方式将它准确地转换为 PHP,因为我从 API 得到空响应,这意味着 - 错误。 I suspect use of wrong post parameters or post method.我怀疑使用了错误的发布参数或发布方法。

In the python code, there's a comment that says what success API return should look like.在 python 代码中,有一条注释说明成功 API 返回应该是什么样子。

EDIT: var_dump($result);编辑: var_dump($result); is returning bool(false) and after enabling error reports, this warning pops out: Warning: file_get_contents(https://kodi.titlovi.com/api/subtitles/gettoken): failed to open stream: HTTP request failed. HTTP/1.1 404 Not Found in /var/www/html/test.php on line 19 bool(false)正在返回 bool(false) 并在启用错误报告后弹出此警告: Warning: file_get_contents(https://kodi.titlovi.com/api/subtitles/gettoken): failed to open stream: HTTP request failed. HTTP/1.1 404 Not Found in /var/www/html/test.php on line 19 bool(false) Warning: file_get_contents(https://kodi.titlovi.com/api/subtitles/gettoken): failed to open stream: HTTP request failed. HTTP/1.1 404 Not Found in /var/www/html/test.php on line 19 bool(false)

PHP - Current script PHP - 当前脚本

<?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 (Working example) Python(工作示例)

  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 puts the parameters in URL query parameters, not POST data. param=dictionary将参数放在 URL 查询参数中,而不是 POST 数据。

The server requires a Content-length: header, which PHP doesn't send by default.服务器需要Content-length: header,PHP 默认不发送。

In order to include \r\n in the header, you have to use double quotes, not single quotes.为了在 header 中包含\r\n ,您必须使用双引号,而不是单引号。

<?php
    error_reporting(-1);
    ini_set('display_errors', 1);

    $api_url = "https://kodi.titlovi.com/api/subtitles";

    $username = "XXX";
    $password = "YYY";

    // sending user login request
    $parameters = array('username' => $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);
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM