对api的curl post请求在使用php时不起作用

对api的curl post请求在使用php时不起作用,php,curl,push,Php,Curl,Push,我正在尝试使用下面的代码使用自己的API发送推送通知。我确信我的服务器中启用了curl。我得到下面的回应 $url = "http://efpushtest.meteor.com/api/push"; # Our new data $data = json_encode(array( 'message' => "this is venkat test push message",

我正在尝试使用下面的代码使用自己的API发送推送通知。我确信我的服务器中启用了curl。我得到下面的回应

        $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);
答复:

{成功:false,消息:意外标记u}


这段代码没有错。

因为您在评论中说它需要post参数,所以您的请求不应该像代码中那样采用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_编码的值传递给post,如下所示:

    $data = array(
            'message' => urlencode("this is venkat test push message"),
            'device' => urlencode("12345")
    );
防止字符串中的任何特殊字符中断您的请求

JSON的旧答案

尝试设置curl请求的标题,以指定您正在向api发布一个“json” 设定我们的选择 curl_setopt$ch,CURLOPT_HTTPHEADER,数组'Content-Type:application/json'; curl_setopt$ch,CURLOPT_POSTFIELDS$data; curl_setopt$ch,CURLOPT_RETURNTRANSFER,true;
由于我在浏览器控制台中执行此操作时得到相同的响应:

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

我想说问题出在你的api代码中

这里的答案似乎是一样的:


该服务正在等待POST参数还是JSON?等待POST参数不使用我设置了它的标题,但仍然存在u triedi尝试使用带有url和POST方法的高级rest api clientchrome扩展测试的相同错误。参数名称数据和输入如下[{消息:这是karteek测试推送,设备:1234}]。它成功地发送了推送通知。这意味着它是json编码的数据或是一个json字符串的普通post数据,但它并没有说太多,因为它可能是chrome扩展显示发布字段的方式。如果您有权访问该服务,您可以检查它是如何处理请求的,并在此处发布相关代码,因为从您得到的响应来看,您似乎希望python服务中包含json,但我们需要查看它是如何处理的。