我尝试使用 YouTube API 及其 ClientLogin .这意味着我需要向他们的服务器发出 POST 请求。
我需要向 https://www.google.com/accounts/ClientLogin 发出请求的 URL .我需要发送的变量是 Email
、Passwd
、source
和 service
。到目前为止,还不错。
我发现这个简洁的函数可以进行 POST 调用(见下文),但它不使用 HTTPS,我认为我必须使用它。一切正常,但我认为我的 POST 请求被转发到 HTTPS,因此它没有给我正确的回调。当我尝试 var_dump
时,返回的数据网页重新加载,我最终到达了 https://www.google.com/accounts/ClientLogin。我在哪里获得正确的数据。但是我当然需要这些数据作为数组或字符串。
那么如何使用 HTTPS 发出 POST 请求呢?
Se 我的代码(我在 Jonas’ Snippet Library 找到的)如下:
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
);
}
这是响应头:
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
我返回的内容是某种形式的自动提交,我认为这是因为我使用 HTTP 而不是 HTTPS:
function autoSubmit() {
document.forms["hiddenpost"].submit();
}
Processing...
那么,我该如何执行 HTTPS POST 请求?
正如 octopusgrabbus 友善地指出的那样,我需要使用端口 443 而不是 80。所以我更改了它,但现在我什么也得不到。
函数返回的 var_dump:
array(3) {
["status"]=>
string(2) "ok"
["header"]=>
string(0) ""
["content"]=>
string(0) ""
}
我没有得到标题,也没有返回内容。怎么了?
最佳答案
我认为您不能直接使用 HTTPS,因为它是使用您要连接的服务器的公共(public)证书加密的 HTTP。也许你可以使用一些 ssl functions在 php 中但是,这会花费您一些时间,坦率地说,还有更简单的事情。
看看cURL (客户端 URL),它支持 GET 和 POST 请求,并且还连接到 https 服务器。
关于php - 如何在 PHP 中通过 HTTPS 发出 POST 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5869271/