用urlfetch替代PHP中的CURL

4

我正在创建一个适用于Google App Engine的应用程序,其中不允许使用CURL。据我所知,urlFetch是最好的替代品。

我不知道是否可以通过urlFetch实现相同的结果,但我真的非常希望有更多经验的人能够帮助我。

计划是将以下CURL请求转换为urlFetch。如果有人能指导我正确的方向,或提出更好的替代方案,我将非常感激。

public function postCall($endpoint, $post_data, $param1, $param2, $json=1, $headers=false) {
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $this->options['url'].$endpoint);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);

if ($headers && is_array($headers)) {
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}

$post_data['req_token'] = $this->hash($param1, $param2);
curl_setopt($ch, CURLOPT_POST, count($post_data));
if (!$headers) 
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
else
    curl_setopt($ch,CURLOPT_POSTFIELDS, $post_data);
$this->debug('POST params: ' . json_encode($post_data));
$result = curl_exec($ch);
if ($result === false) {
    $this->debug('CURL error: '.curl_error($ch));
    return false;
}
$this->debug('HTTP response code' . curl_getinfo($ch, CURLINFO_HTTP_CODE));
$this->debug('POST return ' . $result);

// close connection
curl_close($ch);

if ($json)
    return json_decode(utf8_encode($result), true);
else
    return $result;}

1
我可以建议使用Artax HTTP客户端。它比可怕的curl_* API好了几个光年,而且你知道吗?没有libcurl依赖,所以它可以在任何合理的PHP安装中直接使用。 - user895378
4个回答

9

你是否查看了Urlfetch文档关于PHP封装器的文章?你可以在这个在线shell中进行实验。

代码可以翻译成类似以下的内容:

public function postCall($endpoint, $post_data, $param1, $param2, $json=1, $headers=false) {
  $post_data['req_token'] = $this->hash($param1, $param2);
  $this->debug('POST params: ' . json_encode($post_data));
  $data = http_build_query($post_data);
  $options =
      array("http"=>
        array(
          "method" => "POST",
          "content" => $post_data,
        )
      );
  if ($headers && is_array($headers)) {
      $options["http"]["header"] = $headers;
  }
  $context = stream_context_create($options);
  $result = file_get_contents("http://app.com/path?query=update", false, $context);

  if ($result === FALSE) {
      $this->debug('Error: '. print_r($http_response_header));
      return FALSE;
  }
  $this->debug('Response headers:' . print_r($http_response_header)); // To get the status code you would need to parse that response
  $this->debug('POST return ' . $result);

  if ($json)
      return json_decode(utf8_encode($result), true);
  else
      return $result;
}

谢谢你的回答!我确实看了文档,但是没能弄清楚应该如何翻译。我回家后再看一下。非常感谢你的帮助! - Mats Bakken
哦!SDK示例中的小型销售:D,很酷,因为我不需要按计划上传我的:D - m3nda

6

这太棒了!不需要重写任何代码。真是令人惊叹的东西。 - m3nda
我尝试在Glype PHP网络代理脚本上使用'is not working',也许里面有太多的cURL代码和一些不支持的函数。似乎涉及了一些函数。对这种类型的解决方案非常感兴趣 :O - m3nda

2

有人建议使用azayarni的PURL。但是我要提醒你:在Google App Engine上避免使用它。我花了几天时间试图让它工作,但没有成功:Google PHP Client SDK正在重写一些CURL函数,而PURL会导致很多问题。有些东西可以正常工作,有些则不能。URLFETCH工具更加容易和安全。


1

这是一篇很早的文章,但是需要更新:Google App Engine现在支持PHP 5.5运行时的cURL。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接