【发布时间】:2010-06-10 20:51:08
【问题描述】:
我正在尝试编写一些简单的 php 代码,该代码将发出一个 post 请求,然后从服务器检索 JSON 结果。 这对我来说似乎很简单,但下面的代码根本没有打开连接。
$port = 2057;
$path = "/validate/";
$request = "value1=somevalue&value2=somevalue&value3=somevalue";
$http_request = "POST $path HTTP/1.0\r\n";
$http_request .= "Host: $server\r\n";
$http_request .= "Content-Type: application/x-www-form-urlencoded;\r\n";
$http_request .= "Content-Length: " . strlen($request) . "\r\n";
$http_request .= "\r\n";
$http_request .= $request;
$response = '';
if( false == ( $fs = @fsockopen($server, $port) ) ) {
die ('Could not open socket');
}
fwrite($fs, $http_request);
while ( !feof($fs) )
{
$response .= fgets($fs, 1160);
}
fclose($fs);
此外,我尝试了一种更简单的方法:
$handle = fopen('http://localhost:2057/validate/?'.$request, "r");
或
$response = file_get_contents('http://localhost:2057/validate/' . $request);
但这两种方法都会超时。
我正在尝试连接到我在 Visual Studio 中运行的开发服务器,所以我不确定这是否与超时/连接问题有关。
在此处接受任何建议,只要它们是用 PHP 构建的。
【问题讨论】:
-
你安装了telnet吗?如果不看看here。尝试通过 telnet 连接到您的主机,查看主机是否可访问,如果不能访问,则可能是防火墙问题。
-
我可以在JS中写一个类似的查询并且到达主机没有问题,所以我认为不是防火墙问题。
-
可以安全地假设在第一个示例中您没有复制 $server = "localhost"; 的行吗?
-
您有权访问 Web 服务器日志吗?我经常在安装了类似于 SELinux 的系统上运行 PHP。一般来说,除非明确告知它,否则它甚至不会让您获得文件句柄,更不用说打开 TCP 连接了。您可以在执行此操作时跟踪 httpd 日志吗?
标签: php json post httprequest