带JSON正文的POST请求


76

我想通过PHP在Blogger博客中添加帖子。Google提供了以下示例。如何在PHP中使用它?

您可以通过向带有帖子JSON正文的帖子集合URI发送POST请求来为博客添加帖子:

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..."
}


我还建议您为内容使用JSON,因为您可以创建一个类或函数来返回可以使用json_encode序列化的对象。有关该主题的更多信息,请参见php.net/manual/de/ref.json.php-这只是对该主题的补充建议:-)
Dustin Klein

1
stream_context_create http content字段包含请求的http正文。在b / c中添加此评论,答案中未明确指出。
toddmo '18年

Answers:


137

您需要使用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);

// 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示例的HTTP请求失败// Send the request $response = file_get_contents('https://www.googleapis.com/blogger/v3/blogs/'.$blogID.'/posts/', FALSE, $context);如何修复?
马特2013年

@Matt:cURL示例(第一个)是否起作用?您的webhost / PHP安装可能被阻止file_get_contents。除此之外还有其他错误吗?
火箭Hazmat 2013年

cURL示例可以正常运行,但不会在Blogger博客上创建新帖子。没有错误消息-只是一个空响应。我的令牌有效,并且我再次检查了博客ID。有任何想法吗?
马特

1
我注意到授权标头必须这样构造:Authorization: OAuth {$authToken}
SIFE,2013年

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令牌。
火箭Hazmat 2013年

我不确定令牌的外观。对于格式CURLOPT_USERPWD IS username:password。这是放在Authorization标题中的内容,因此它的结果应与添加手动标题相同Authorization: base64 of OAuth 2.0 token here
MaX

尝试了代码,然后出现此错误:Warning: curl_setopt() expects parameter 1 to be resource, null given令牌看起来像这样:btw:ya29.AHES6ZTIXVmG56O1SWM9IZpTUIQCUFQ9C2AQdp8AgHL6emMN我需要更改什么参数?
马特2013年

抱歉,忘记初始化卷曲。我已使用来更新脚本$ch = curl_init();
MaX

现在可以正常使用,但是Blogger发送此错误:Error: 401 HTTP Basic Authentication is not supported for this API是因为curl_setopt($ch, CURLOPT_USERPWD,"[token]);"
马特


2

我使API根据@Rocket Hazmat,@ dbau和@maraca代码通过网站上的表单将数据发送到prosperworks。我希望这会对某人有所帮助:

<?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);
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.