如何在PHP中通过HTTPS发出POST请求?

jam*_*lin 4 php https post youtube-api

我尝试使用YouTube API及其ClientLogin.这意味着我需要向他们的服务器发出POST请求.

我需要向https://www.google.com/accounts/ClientLogin提出请求的网址.我需要发送的变量是Email,Passwd,sourceservice.到现在为止还挺好.

我发现这个简洁的函数可以进行POST调用(见下文),但它不使用HTTPS,我认为我必须使用它.这一切都有效,但我认为我的POST请求被转发到HTTPS,因此它没有给我正确的回调.当我尝试时var_dump,返回的数据网页会重新加载,最后我会访问https://www.google.com/accounts/ClientLogin,获取正确的数据.但是我当然需要将这些数据作为数组或字符串.

那么如何使用HTTPS发出POST请求呢?

请在下面找到我的代码(我在Jonas的代码段库中找到):

function post_request($url, $data, $referer='') {

        $data = http_build_query($data);

        $url = parse_url($url);     

        $host = $url['host'];
        $path = $url['path'];

        $fp = fsockopen($host, 80, $errno, $errstr, 30);

        if ($fp){

            fputs($fp, "POST $path HTTP/1.1\r\n");
            fputs($fp, "Host: $host\r\n");

            if ($referer != '')
                fputs($fp, "Referer: $referer\r\n");

            fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
            fputs($fp, "Content-length: ". strlen($data) ."\r\n");
            fputs($fp, "Connection: close\r\n\r\n");
            fputs($fp, $data);

            $result = ''; 
            while(!feof($fp)) {

                $result .= fgets($fp, 128);
            }
        }
        else { 
            return array(
                'status' => 'err', 
                'error' => "$errstr ($errno)"
            );
        }

        fclose($fp);

        $result = explode("\r\n\r\n", $result, 2);

        $header = isset($result[0]) ? $result[0] : '';
        $content = isset($result[1]) ? $result[1] : '';

        return array(
            'status' => 'ok',
            'header' => $header,
            'content' => $content
        );
    }
Run Code Online (Sandbox Code Playgroud)

这是响应头:

HTTP/1.1 200 OK
Content-Type: text/html; charset=UTF-8
Date: Tue, 03 May 2011 12:15:20 GMT
Expires: Tue, 03 May 2011 12:15:20 GMT
Cache-Control: private, max-age=0
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Content-Length: 728
Server: GSE
Connection: close
Run Code Online (Sandbox Code Playgroud)

我得到的内容是某种形式的自动提交,我认为这是因为我使用HTTP而不是HTTPS:

    function autoSubmit() {
      document.forms["hiddenpost"].submit();
    }

Processing...
Run Code Online (Sandbox Code Playgroud)

那么,我该如何进行HTTPS POST请求呢?


正如octopusgrabbus指出的那样,我需要使用端口443而不是80.所以我改变了这一点,但现在我什么都没有回来.

函数返回的var_dump:

array(3) {
  ["status"]=>
  string(2) "ok"
  ["header"]=>
  string(0) ""
  ["content"]=>
  string(0) ""
}
Run Code Online (Sandbox Code Playgroud)

我没有头,也没有内容.怎么了?

Car*_*rós 6

我认为您无法直接与HTTPS通信,因为它是使用您要连接的服务器的公共证书进行HTTP加密的.也许你可以在php中使用一些ssl函数.但是,这将花费你一些时间,坦率地说,有更简单的事情.

只需看看cURL(客户端URL),它支持GET和POST请求,还可以连接到https服务器.