2014-10-18 128 views
0

我試圖使用我自己的API使用下面的代碼發送推送通知。我確定我的服務器啓用了curl。作爲迴應,我得到了下面的結論。curl對api的post請求無法使用php

 $url = "http://efpushtest.meteor.com/api/push"; 

     # Our new data 
     $data = json_encode(array(
       'message' => "this is venkat test push message", 
       'device' => "12345" 
     )); 

     $ch = curl_init($url); 

     # Setting our options 
     curl_setopt($ch, CURLOPT_POST, 1); 
     curl_setopt($ch, CURLOPT_POSTFIELDS, $data); 
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 

     # Get the response 
     $result = curl_exec($ch); 
     curl_close($ch); 

響應:

{ 「成功」:假的, 「消息」: 「意外令牌U」}

,我沒有得到我在哪裏,此代碼腳麻。

+0

服務正在等待用於'POST'參數或'JSON'? – Kypros 2014-10-18 14:29:24

+0

等待帖子參數 – 2014-10-18 14:30:46

回答

0

既然你在評論中說它期望發佈參數,你的請求不應該像你的代碼那樣被json編碼。來處理一個適當的方式將是發佈領域,像這樣:

$url = "http://efpushtest.meteor.com/api/push"; 

    # Our new data 
    $data = array(
      'message' => "this is venkat test push message", 
      'device' => "12345" 
    ); 

    $ch = curl_init($url); 

    // build the post string here 
    foreach($data as $key=>$value) { 
     $fields_string .= $key.'='.$value.'&'; 
    } 

    rtrim($fields_string, '&'); 

    # Setting our options 
    curl_setopt($ch, CURLOPT_POST, count($data)); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 

    # Get the response 
    $result = curl_exec($ch); 
    curl_close($ch); 

,你實際上張貼參數POST參數傳遞它們在形式的字符串,你會在GET看到。您的例子將後:

消息=這是venkat測試推送消息&設備= 12345

如果我是你,我也所以其傳遞url_encoded值後作爲更新數組宣言在:

$data = array(
      'message' => urlencode("this is venkat test push message"), 
      'device' => urlencode("12345") 
    ); 

,以防止任何特殊字符字符串中打破你的請求

OLD答案JSON

嘗試將捲曲的請求的標題來指定要發佈一個`json`的API #設置我們的選擇 curl_setopt($ CH,CURLOPT_HTTPHEADER,陣列(」內容類型:應用/ JSON')); curl_setopt($ ch,CURLOPT_POSTFIELDS,$ data); curl_setopt($ ch,CURLOPT_RETURNTRANSFER,true);
+0

沒有用,我設置了標頭,還是同樣的錯誤,你試過 – 2014-10-18 14:31:50

+0

請檢查我的答案的更新。 – Kypros 2014-10-18 14:39:39

+0

我試圖使用url和post方法使用高級rest api客戶端(Chrome擴展)進行測試。參數名稱數據和輸入爲[{「message」:「這是karteek test Push」,「device」:「1234」}]。它成功發送推送通知。這是什麼意思是它是json編碼的數據還是普通的post數據 – 2014-10-18 14:45:28

0

因爲我得到同樣的迴應在瀏覽器控制檯這樣做:

$.post("/api/push/", { "message" : "this is venkat test push message","device" : "12345" });

我想說的問題是在您的API代碼

這個答案在這裏似乎說的一樣東西:

https://stackoverflow.com/a/13022566/4152193