【问题标题】:How to get the HTTP request as a string from PHP HTTP Stream如何从 PHP HTTP Stream 获取 HTTP 请求作为字符串
【发布时间】:2011-07-29 08:30:46
【问题描述】:

我正在使用 PHP Streams 通过 fopen() 进行 HTTP 调用。我想在通过 fopen() 发送 HTTP 请求之前将其打印为字符串(标题和内容)。

是否有处理流上下文变量的函数来执行此操作?如果是这样,有人会好心发布一个简短的例子吗?

这是一个函数,它需要一个 URL,获取它并返回内容:

function do_post_request ($url, $content, $cookie = null) {
  $headers = array("Content-type: application/x-www-form-urlencoded",
                   $cookie);

  $all_headers = implode("\r\n", $headers)."\r\n";
  $params = array('http' => array("method" => "POST",
                                  "content" => $content,
                                  "header" => $all_headers,
                                 ),
                 );

  $ctx = stream_context_create($params);
  $fp = fopen($url, 'rb', false, $ctx);
  if (empty($fp)) {
    throw new Exception("$url: Failed");
  }
  $resp = stream_get_contents($fp);

  if (empty($resp)) {
    throw new Exception("error: bad fetch");
  }
  return $resp
}

【问题讨论】:

  • 我不相信你能做到。在进行任何请求之前,您需要将这些标头用于何处?
  • 简而言之,用于调试。我正在连接到自定义 Web 服务,我需要确保 HTTP 客户端标头和内容都符合我的预期。
  • 所以。事后(即不是在发送之前)就足够了吗?我要么通过使用cURLHTTPRequest 来做到这一点,它们本身就支持这一点。如果你真的需要 fopen 和上下文参数,我认为你必须创建一个代理包装器。

标签: php http stream


【解决方案1】:

我会使用 PEAR 的 HTTP_Request2,它支持拦截和记录发送的标头。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多