带有JSON主体的POST请求

86

我想通过PHP向Blogger博客添加一篇文章。 谷歌提供了以下示例。如何在PHP中使用这个呢?

您可以通过向帖子集合URI发送POST请求并附加一个帖子JSON主体来为博客添加帖子:

POST https://www.googleapis.com/blogger/v3/blogs/8070105920543249955/posts/
Authorization: /* OAuth 2.0 token here */
Content-Type: application/json

{
  "kind": "blogger#post",
  "blog": {
    "id": "8070105920543249955"
  },
  "title": "A new post",
  "content": "With <b>exciting</b> content..."
}

1
可能是使用PHP发送JSON POST的重复问题。 - freejosh
我还建议您使用JSON来处理内容,因为您可以创建一个类或函数,该类或函数将返回一个对象,您可以使用json_encode进行序列化。有关该主题的更多信息,请访问此处:http://www.php.net/manual/de/ref.json.php - 这只是对此主题的额外建议 :-) - Dustin Klein
1
stream_context_create函数中的http字段的content属性包含了请求的HTTP正文。添加此注释是因为答案中没有明确说明。 - toddmo
5个回答

152
你需要使用cURL库来发送该请求。
<?php
// Your ID and token
$blogID = '8070105920543249955';
$authToken = 'OAuth 2.0 token here';

// The data to send to the API
$postData = array(
    'kind' => 'blogger#post',
    'blog' => array('id' => $blogID),
    'title' => 'A new post',
    'content' => 'With <b>exciting</b> content...'
);

// Setup cURL
$ch = curl_init('https://www.googleapis.com/blogger/v3/blogs/'.$blogID.'/posts/');
curl_setopt_array($ch, array(
    CURLOPT_POST => TRUE,
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_HTTPHEADER => array(
        'Authorization: '.$authToken,
        'Content-Type: application/json'
    ),
    CURLOPT_POSTFIELDS => json_encode($postData)
));

// Send the request
$response = curl_exec($ch);

// Check for errors
if($response === FALSE){
    die(curl_error($ch));
}

// Decode the response
$responseData = json_decode($response, TRUE);

// Close the cURL handler
curl_close($ch);

// Print the date from the response
echo $responseData['published'];

如果由于某种原因,您不能/不想使用cURL,您可以这样做:

<?php
// Your ID and token
$blogID = '8070105920543249955';
$authToken = 'OAuth 2.0 token here';

// The data to send to the API
$postData = array(
    'kind' => 'blogger#post',
    'blog' => array('id' => $blogID),
    'title' => 'A new post',
    'content' => 'With <b>exciting</b> content...'
);

// Create the context for the request
$context = stream_context_create(array(
    'http' => array(
        // http://www.php.net/manual/en/context.http.php
        'method' => 'POST',
        'header' => "Authorization: {$authToken}\r\n".
            "Content-Type: application/json\r\n",
        'content' => json_encode($postData)
    )
));

// Send the request
$response = file_get_contents('https://www.googleapis.com/blogger/v3/blogs/'.$blogID.'/posts/', FALSE, $context);

// Check for errors
if($response === FALSE){
    die('Error');
}

// Decode the response
$responseData = json_decode($response, TRUE);

// Print the date from the response
echo $responseData['published'];

5
非常好的教程!甚至包括了 JSON 部分 :-) - Dustin Klein
我在“纯”PHP示例的这一行收到错误消息failed to open stream: HTTP request failed// Send the request $response = file_get_contents('https://www.googleapis.com/blogger/v3/blogs/'.$blogID.'/posts/', FALSE, $context); 该如何修复? - Matt
@Matt:cURL示例(第一个)是否有效?你的网络主机/PHP安装可能会阻止file_get_contents。除此之外,还有其他错误吗? - gen_Eric
@Matt:你是怎么获取这个token的?你确定它是有效的吗? - gen_Eric
1
我注意到授权头必须这样构建:Authorization: OAuth {$authToken} - SIFE
显示剩余6条评论

13

我认为cURL会是一个不错的解决方案。虽然我没有测试过,但你可以尝试以下代码:

$body = '{
  "kind": "blogger#post",
  "blog": {
    "id": "8070105920543249955"
  },
  "title": "A new post",
  "content": "With <b>exciting</b> content..."
}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.googleapis.com/blogger/v3/blogs/8070105920543249955/posts/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json","Authorization: OAuth 2.0 token here"));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
$result = curl_exec($ch);

我认为CURLOPT_USERPWDCURLAUTH_BASIC不能正确地在Authorization头中发送OAuth令牌。 - gen_Eric
我不确定令牌的样子。CURLOPT_USERPWD 的格式为 用户名:密码。这是放入 “授权” 标头的内容,因此它应该与添加手动标头 Authorization: OAuth 2.0 令牌的 base64 得到相同的结果。 - MaX
尝试了代码后,我得到了这个错误:警告:curl_setopt()期望参数1为资源,但给出了null。顺便说一下,令牌看起来像这样:ya29.AHES6ZTIXVmG56O1SWM9IZpTUIQCUFQ9C2AQdp8AgHL6emMN。我需要更改哪个参数? - Matt
抱歉,忘记初始化curl了。我已经在脚本中更新了 $ch = curl_init(); - MaX
更改了代码后,我从Blogger收到了一个新的错误消息:"error": { "errors": [ { "domain": "global", "reason": "required", "message": "需要登录", "locationType": "header", "location": "Authorization" } ], "code": 401, "message": "需要登录" } } 你有什么想法? - Matt
显示剩余4条评论

3

3

我基于@Rocket Hazmat、@dbau和@maraca的代码,制作了一个可以通过网站表单将数据发送到prosperworks的API。希望能对某些人有所帮助。

<?php

if(isset($_POST['submit'])) {
    //form's fields name:
    $name = $_POST['nameField'];
    $email = $_POST['emailField'];

    //API url:
    $url = 'https://api.prosperworks.com/developer_api/v1/leads';

    //JSON data(not exact, but will be compiled to JSON) file:
    //add as many data as you need (according to prosperworks doc):
    $data = array(
                            'name' => $name,
                            'email' => array('email' => $email)
                        );

    //sending request (according to prosperworks documentation):
    // use key 'http' even if you send the request to https://...
    $options = array(
        'http' => array(
            'header'  => "Content-Type: application/json\r\n".
             "X-PW-AccessToken: YOUR_TOKEN_HERE\r\n".
             "X-PW-Application:developer_api\r\n".
             "X-PW-UserEmail: YOUR_EMAIL_HERE\r\n",
            'method'  => 'POST',
            'content' => json_encode($data)
        )
    );

    //engine:
    $context  = stream_context_create($options);
    $result = file_get_contents($url, false, $context);
    if ($result === FALSE) { /* Handle error */ }
    //compiling to JSON (as wrote above):
    $resultData = json_decode($result, TRUE);
    //display what was sent:
    echo '<h2>Sent: </h2>';
    echo $resultData['published'];
    //dump var:
    var_dump($result);

}
?>
<html>
    <head>
    </head>

    <body>

        <form action="" method="POST">
            <h1><?php echo $msg; ?></h1>
            Name: <input type="text" name="nameField"/>
            <br>
            Email: <input type="text" name="emailField"/>
            <input type="submit" name="submit" value="Send"/>
        </form>

    </body>
</html>

0
<?php
// Example API call
$data = array(array (
    "REGION" => "MUMBAI",
    "LOCATION" => "NA",
    "STORE" => "AMAZON"));
// json encode data
$authToken = "xxxxxxxxxx";
$data_string = json_encode($data); 
// set up the curl resource
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://domainyouhaveapi.com");   
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type:application/json',       
    'Content-Length: ' . strlen($data_string) ,
    'API-TOKEN-KEY:'.$authToken ));   // API-TOKEN-KEY is keyword so change according to ur key word. like authorization 
// execute the request
$output = curl_exec($ch);
//echo $output;
// Check for errors
if($output === FALSE){
    die(curl_error($ch));
}
echo($output) . PHP_EOL;
// close curl resource to free up system resources
curl_close($ch);

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