2013-06-04 59 views
57

Tôi muốn thêm post to a Blogger blog qua PHP. Google đã cung cấp ví dụ bên dưới. Làm thế nào để sử dụng nó với PHP?Yêu cầu POST với phần thân JSON

You can add a post for a blog by sending a POST request to the post collection URI with a post JSON body:

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

thể trùng lặp của [Gửi bài json sử dụng php] (http://stackoverflow.com/questions/6213509/send-json-post-using-php) – freejosh

+0

tôi cũng sẽ khuyên bạn nên sử dụng JSON cho nội dung của bạn, vì bạn có thể tạo một lớp hoặc hàm sẽ trả về một đối tượng mà bạn có thể tuần tự hóa với json_encode. Thông tin thêm về chủ đề đó bạn có thể tìm thấy ở đây: http://www.php.net/manual/de/ref.json.php - Đây chỉ là một gợi ý bổ sung cho chủ đề này :-) –

Trả lời

98

Bạn cần sử dụng cURL library để gửi yêu cầu này.

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

Nếu vì một lý do nào, bạn không thể/không muốn sử dụng cURL, bạn có thể làm điều này:

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

Hướng dẫn tuyệt vời! Ngay cả phần json được bao gồm :-) –

+0

@DustinKlein: Cảm ơn!Tôi đã cố gắng hết sức mình :-) –

+0

Tôi nhận được lỗi ** không thể mở luồng: yêu cầu HTTP không thành công ** đối với ví dụ PHP "thuần túy" ở dòng này: '// Gửi yêu cầu $ response = file_get_contents (' https://www.googleapis.com/blogger/v3/blogs/'.$blogID.'/posts/ ', FALSE, $ context); 'Cách sửa lỗi? – Matt

8

Tôi nghĩ cURL sẽ là một giải pháp tốt. Đây không phải là thử nghiệm, nhưng bạn có thể thử một cái gì đó như thế này:

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

Tôi không nghĩ rằng 'CURLOPT_USERPWD 'và' CURLAUTH_BASIC' sẽ gửi mã thông báo OAuth chính xác trong tiêu đề 'Ủy quyền'. –

+0

Tôi không chắc chắn mã thông báo trông như thế nào. Định dạng cho 'CURLOPT_USERPWD' là 'tên người dùng: mật khẩu'. Đây là những gì được đưa vào tiêu đề 'Authorization', vì vậy nó phải là kết quả tương tự như thêm tiêu đề thủ công' Authorization: base64 của mã thông báo OAuth 2.0 tại đây'. – MaX

+0

Đã thử mã và tôi nhận được lỗi này: 'Cảnh báo: curl_setopt() hy vọng tham số 1 là tài nguyên, null được cung cấp' Mã thông báo trông giống như btw này:' ya29.AHES6ZTIXVmG56O1SWM9IZpTUIQCUFQ9C2AQdp8AgHL6emMN' Thông số nào cần thay đổi? – Matt

3

Nếu bạn không muốn sử dụng CURL, bạn có thể tìm thấy một số ví dụ về stackoverflow, chỉ cần như thế này đây: How do I send a POST request with PHP?. Tôi khuyên bạn nên xem một vài hướng dẫn về cách sử dụng các phương thức GET và POST trong PHP hoặc chỉ cần xem hướng dẫn sử dụng php.net tại đây: httprequest::send. Bạn có thể tìm thấy nhiều hướng dẫn: HTTP POST from PHP, without cURL và cứ thế ...

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

tôi đã thực hiện API gửi dữ liệu mẫu trên trang web để thịnh vượng dựa trên @Rocket Hazmat, @dbau và @maraca code. Tôi hy vọng, nó sẽ giúp ai đó:

<?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> 
Các vấn đề liên quan