发出POST请求

时间:2010-10-09 23:17:24

标签: php api curl

我想知道如何制作HTTP POST请求,就像在那里http://code.google.com/apis/documents/docs/3.0/developers_guide_protocol.html#UploadingMetadata所描述的那样(创建一个空文档)。 我的代码如下所示:

<?php

$headers = array(
    "POST /feeds/default/private/full HTTP/1.1",
    "Host: docs.google.com",
    "GData-Version: 3.0",
    "Content-Length: 287",
    "Content-Type: application/atom+xml"
);

$data = "<?xml version='1.0' encoding='UTF-8'?>";
$data .= "<entry xmlns='http://www.w3.org/2005/Atom'>";
$data .= "<category scheme='http://schemas.google.com/g/2005#kind'";
$data .= "term='http://schemas.google.com/docs/2007#document'/>";
$data .= "<title>new document</title>";
$data .= "</entry>";

$ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, "http://google.com/docs/feeds/default/private/full");
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, true);

$result = curl_exec($ch);

print_r($result);

?>

那里有什么问题?我正确地做了请求吗?

2 个答案:

答案 0 :(得分:3)

$data = "<?xml version='1.0' encoding='UTF-8'?>";

替换为:

$data = "<"."?xml version='1.0' encoding='UTF-8'?".">";

和...

$data .= "term='http://schemas.google.com/docs/2007#document'/>";

使用:

$data .= " term='http://schemas.google.com/docs/2007#document'/>";

哦,最后,你不应该print_r结果; print_r用于数组和对象,而不是字符串(curl_exec返回字符串或null / false),而是使用var_dump($result);

答案 1 :(得分:0)

此外,您的自定义标题看起来很奇怪:

POST根本不是标题,所以这是完全错误的。

主机:由curl本身添加,没有任何设置。

Content-Length:由curl本身完成,如果你弄错了,你大多会冒着令人困惑的卷曲风险。