PHP发布请求以检索JSON

时间:2010-06-10 20:51:08

标签: php json post httprequest

我正在尝试编写一些简单的PHP代码,它将发出一个帖子请求,然后从服务器检索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构建的,就可以在这里打开任何建议。

3 个答案:

答案 0 :(得分:2)

有很多纯PHP HTTP处理程序可能对你有用。

尝试使用PEAR's HTTP_ClientZend_Http_Client,您只需将其与应用程序捆绑在一起。

如果你自己写完了,请尝试使用streams。有comprehensive set of HTTP stream options可供选择。

答案 1 :(得分:2)

尝试使用HTTP_Request2;它不是标准的PHP,但您可以将它与您的应用程序一起分发,这样您就不必担心它是否已安装。

以下是我用于将文档发布到转换服务器的类的片段;你可以发布你喜欢的任何内容,并以类似的方式得到结果。

$request = new HTTP_Request2('http://whereveryouwant:80/foo/');
$request->setMethod(HTTP_Request2::METHOD_POST)
    ->setConfig('timeout', CONVERT_SERVER_TIMEOUT)
    ->setHeader('Content-Type', 'multipart/form-data')
    ->addPostParameter('outputFormat', $outputType);
$request->addUpload('inputDocument', $inputFile);
$result = $request->send();
if ($result->getStatus() == 200) {
    return $result->getBody();
} else {
    return false;
}

答案 2 :(得分:0)

使用http扩展名http://fr.php.net/manual/en/function.http-post-data.php

写这个可能更简单