在PHP中发起REST API请求

3

对于这个问题的新手提问,我表示歉意。我正在研究将一个网站的API集成到我的网站中。以下是他们文档中的一些引用:

目前我们仅支持XML, 调用我们的API时,HTTP Accept header内容类型必须设置为“application/xml”。

该API使用 PUT 请求方法。

我有要发送的XML和要发送到的URL,但我应该如何构建适当的HTTP请求以及获取返回的XML?

提前致谢。

2个回答

12

你可以使用 file_get_contentsstream_context_create 来创建一个请求并读取响应。类似这样的代码可以实现:

$opts = array(
  "http" => array(
    "method" => "PUT",
    "header" => "Accept: application/xml\r\n",
    "content" => $xml
  )
);

$context = stream_context_create($opts);
$response = file_get_contents($url, false, $context);

谢谢你,但好像不起作用。$response 里面什么都没有 :( 嗯。 - Chuck Le Butt
PHP.net网站显示stream_create_context函数不存在。您是不是想查看http://us3.php.net/manual/en/function.stream-context-create.php? - jerrygarciuh
1
@jerrygarciuh 绝对是打错了,我的代码实际上使用了stream_context_create。 - alexn

6

这是我实际使用的方法:

$fp = fsockopen("ssl://api.staging.example.com", 443, $errno, $errstr, 30);


if (!$fp) 
{
    echo "<p>ERROR: $errstr ($errno)</p>";
    return false;
} 
else 
{
    $out = "PUT /path/account/ HTTP/1.1\r\n";
    $out .= "Host: api.staging.example.com\r\n";
    $out .= "Content-type: text/xml\r\n";
    $out .= "Accept: application/xml\r\n";
    $out .= "Content-length: ".strlen($xml)."\r\n";
    $out .= "Connection: Close\r\n\r\n";
    $out .= $xml;

    fwrite($fp, $out);

    while (!feof($fp)) 
    {
        echo fgets($fp, 125);
    }

    fclose($fp);
}

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