POST,DELETE不通过stream_context_create()/ fopen()发送响应

时间:2011-10-28 14:44:00

标签: php http http-post fopen http-delete

我有以下用于通过HTTP发布数据的代码

        $opts = array (
                'http' => array (
                    'method' => "POST",
                    'header' => $auth ,
                    //  . "Content-Type: " . $content_type . "\r\n"
                    //  . "Content-length: " . strlen($data) . "\r\n",
                    'user_agent' => RESTClient :: USER_AGENT,
                    'content' => $data                      
                )
        );
        $context = stream_context_create($opts);
        $fp = fopen($url, 'r', false, $context);
        $result = "";
        while ($str = fread($fp,1024)) {
            $result .= $str;
        }
        fclose($fp);


     Return $result;

当我在数据库中查看已发布的已发布数据时发布,但是,我的代码应该返回响应。当我使用cURL而不是通过此方法时,响应正常工作。我错过了什么吗?

1 个答案:

答案 0 :(得分:0)

由于缺少Content-type而发出的警告/通知

<?php
class RESTClient {
    const USER_AGENT='Mozilla';
}
$url = 'http://social.msdn.microsoft.com/Search/en-US/';
$data = 'query=test&ac=3';
$auth = '';

// <-- unaltered code
$opts = array (
    'http' => array (
        'method' => "POST",
        'header' => $auth ,
        //  . "Content-Type: " . $content_type . "\r\n"
        //  . "Content-length: " . strlen($data) . "\r\n",
        'user_agent' => RESTClient :: USER_AGENT,
        'content' => $data
    )
);
$context = stream_context_create($opts);
$fp = fopen($url, 'r', false, $context);
$result = "";
while ($str = fread($fp,1024)) {
    $result .= $str;
}
fclose($fp);
//  unaltered code -->
echo $result;

对我来说很好。
此代码段是否会在系统上产生所描述的行为?


btw:您也可以使用file_get_contents代替fopen / while / fread / fclose。