POST-Anfrage mit JSON-Body


76

Ich möchte einen Beitrag zu einem Blogger-Blog über PHP hinzufügen . Google hat das folgende Beispiel bereitgestellt. Wie benutzt man das mit PHP?

Sie können einen Beitrag für ein Blog hinzufügen, indem Sie eine POST-Anforderung mit einem JSON-Textkörper an den Beitragssammlungs-URI senden:

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
Mögliches Duplikat von Send json post using php
— freejosh

Ich würde auch empfehlen, JSON für Ihren Inhalt zu verwenden, da Sie eine Klasse oder Funktion erstellen können, die ein Objekt zurückgibt, das Sie mit json_encode serialisieren können. Weitere Informationen zu diesem Thema finden Sie hier: php.net/manual/de/ref.json.php - Dies ist nur ein zusätzlicher Vorschlag zu diesem Thema :-)
— Dustin Klein

1
Das stream_context_create http contentFeld enthält den http-Text für die Anforderung. Durch Hinzufügen dieses Kommentars wurde dies in der Antwort nicht ausdrücklich angegeben.
— Toddmo

Antworten:


137

Sie müssen die cURL-Bibliothek verwenden , um diese Anforderung zu senden.

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

Wenn Sie cURL aus irgendeinem Grund nicht verwenden können / möchten, können Sie dies tun:

<?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
Tolles Tutorial! Sogar der JSON-Teil ist enthalten :-)
— Dustin Klein

Ich erhalte den Fehler , dass der Stream nicht geöffnet werden konnte: HTTP-Anforderung für das "reine" PHP-Beispiel in dieser Zeile fehlgeschlagen : // Send the request $response = file_get_contents('https://www.googleapis.com/blogger/v3/blogs/'.$blogID.'/posts/', FALSE, $context);Wie kann ich das Problem beheben?
— Matt

@Matt: Funktioniert das cURL-Beispiel (erstes)? Ihre Webhost / PHP-Installation könnte blockiert sein file_get_contents. Gibt es sonst noch den Fehler?
— Rocket Hazmat

Das cURL-Beispiel funktioniert fehlerfrei, erstellt jedoch keinen neuen Beitrag im Blogger-Blog. Es gibt keine Fehlermeldungen - nur eine leere Antwort. Mein Token ist gültig und ich habe die Blog-ID überprüft. Irgendwelche Ideen?
— Matt

1
Mir ist aufgefallen, dass der Autorisierungsheader folgendermaßen aufgebaut sein muss : Authorization: OAuth {$authToken}.
— SIFE

13

Ich denke, cURL wäre eine gute Lösung. Dies wird nicht getestet, aber Sie können Folgendes ausprobieren:

$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);

Ich denke nicht CURLOPT_USERPWDund CURLAUTH_BASICwerde das OAuth-Token korrekt im AuthorizationHeader senden .
— Rocket Hazmat

Ich bin mir nicht sicher, wie der Token aussieht. Das Format für CURLOPT_USERPWD ist username:password. Dies wird in den AuthorizationHeader eingefügt, daher sollte dies das gleiche Ergebnis sein wie das Hinzufügen eines manuellen Headers Authorization: base64 of OAuth 2.0 token here.
— MaX

Versuchte den Code und ich bekomme folgende Fehlermeldung: Warning: curl_setopt() expects parameter 1 to be resource, null givenDas Token sieht übrigens so aus: ya29.AHES6ZTIXVmG56O1SWM9IZpTUIQCUFQ9C2AQdp8AgHL6emMNWelchen Parameter muss ich ändern?
— Matt

Entschuldigung, ich habe vergessen, Curl zu initialisieren. Ich habe das Skript mit aktualisiert $ch = curl_init();.
— MaX

Es funktioniert jetzt, aber Blogger sendet diesen Fehler: Error: 401 HTTP Basic Authentication is not supported for this APILiegt es an curl_setopt($ch, CURLOPT_USERPWD,"[token]);"?
— Matt


2

Ich habe API dazu gebracht, Daten über ein Formular auf der Website an prosperworks zu senden, basierend auf @ Rocket Hazmat-, @ dbau- und @ maraca-Code. Ich hoffe, es wird jemandem helfen:

<?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);
Durch die Nutzung unserer Website bestätigen Sie, dass Sie unsere Cookie-Richtlinie und Datenschutzrichtlinie gelesen und verstanden haben.
Licensed under cc by-sa 3.0 with attribution required.