【问题标题】:POST request with JSON body带有 JSON 正文的 POST 请求
【发布时间】:2013-05-30 23:51:32
【问题描述】:

我想通过 PHP 添加一个post to a Blogger blog。 谷歌提供了下面的例子。如何在 PHP 中使用它?

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

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

【问题讨论】:

  • Send json post using php的可能重复
  • 我还建议您对内容使用 JSON,因为您可以创建一个类或函数,该类或函数将返回一个您可以使用 json_encode 序列化的对象。您可以在此处找到有关该主题的更多信息:php.net/manual/de/ref.json.php - 这只是对该主题的附加建议 :-)
  • stream_context_create http content 字段包含请求的 http 正文。添加此评论 b/c 这未在答案中明确说明。

标签: php json post


【解决方案1】:

您需要使用cURL library 发送此请求。

<?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'];

【讨论】:

  • 很棒的教程!甚至包括 json 部分 :-)
  • 我收到错误无法打开流:HTTP 请求失败,“纯”PHP 示例在此行:// Send the request $response = file_get_contents('https://www.googleapis.com/blogger/v3/blogs/'.$blogID.'/posts/', FALSE, $context); 如何解决?跨度>
  • @Matt:cURL 示例(第一个)有效吗?您的虚拟主机/PHP 安装可能会阻止 file_get_contents。除此之外还有错误吗?
  • cURL 示例可以正常运行,但不会在 Blogger 博客上创建新帖子。没有错误消息 - 只是一个空响应。我的令牌有效,我仔细检查了博客 ID。有什么想法吗?
  • 我注意到授权标头必须像这样构造:Authorization: OAuth {$authToken}.
【解决方案2】:

我认为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 令牌。
  • 我不确定令牌的外观。 CURLOPT_USERPWD 的格式是 username:password。这是放入 Authorization 标头的内容,因此它应该与添加手动标头 Authorization: base64 of OAuth 2.0 token here 的结果相同。
  • 尝试了代码,我得到了这个错误:Warning: curl_setopt() expects parameter 1 to be resource, null given 令牌看起来像这样顺便说一句:ya29.AHES6ZTIXVmG56O1SWM9IZpTUIQCUFQ9C2AQdp8AgHL6emMN 我需要更改什么参数?
  • 抱歉,忘记初始化 curl。我用$ch = curl_init();更新了脚本。
  • 它现在可以工作,但 Blogger 发送此错误:Error: 401 HTTP Basic Authentication is not supported for this API 是因为 curl_setopt($ch, CURLOPT_USERPWD,"[token]);" 吗?
【解决方案3】:

如果你不想使用 CURL,你可以在 stackoverflow 上找到一些例子,就像这里的这个:How do I send a POST request with PHP?。我建议您观看一些关于如何在 PHP 中使用 GET 和 POST 方法的教程,或者只是看看这里的 php.net 手册:httprequest::send。可以找到很多教程:HTTP POST from PHP, without cURL等等……

【讨论】:

    【解决方案4】:

    我基于@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>
    

    【讨论】:

      【解决方案5】:
      <?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);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-08-14
        • 2016-09-29
        • 2016-09-24
        • 2015-12-02
        • 2019-02-11
        • 1970-01-01
        • 1970-01-01
        • 2019-12-13
        相关资源
        最近更新 更多