【问题标题】:curl post request to an api was not working using php使用 php 对 api 的 curl 发布请求不起作用
【发布时间】:2014-12-13 23:06:33
【问题描述】:

我正在尝试使用以下代码使用我自己的 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);

回复:

{"success":false,"message":"Unexpected token u"}

我不知道这段代码哪里出错了。

【问题讨论】:

  • 服务是否在等待POST参数或JSON
  • 等待发布参数

标签: php curl push


【解决方案1】:

由于您在评论中说它需要发布参数,因此您的请求不应像您的代码中那样采用 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 中看到的那样。您的示例将发布:

message=这是 venkat 测试推送消息&device=12345

如果我是你,我也会更新数组声明,以便将 url_encoded 值传递给帖子,如下所示:

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

防止字符串中的任何特殊字符破坏您的请求

JSON 的旧答案

尝试设置 curl 请求的标头以指定您将 `json` 发布到 api # 设置我们的选项 curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

【讨论】:

  • 没用,我设置了标题也还是同样的错误,你试过了吗
  • 我尝试使用带有 url 和 post 方法的高级 rest api 客户端(chrome 扩展)进行测试。参数名称数据并输入为 this [{"message": "This is karteek test Push", "device": "1234"}]。它成功发送了推送通知。这是什么意思是json编码的数据还是普通的post数据
  • 这是一个 json 字符串,但它并没有说太多,因为它可能是 chrome 扩展显示您发布的字段的方式。如果您有权访问该服务,您可以检查它如何处理请求并在此处发布相关代码,因为从您得到的响应中,您似乎在 python 服务中期待 json,但我们需要看看如何它可以确定地处理它。
【解决方案2】:

因为我在浏览器控制台中得到相同的响应:

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

我会说问题出在您的 api 代码中

这里的答案似乎说的是同一件事:

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

【讨论】:

    猜你喜欢
    • 2019-12-19
    • 1970-01-01
    • 1970-01-01
    • 2020-08-14
    • 2019-01-27
    • 2022-10-24
    • 2017-10-18
    • 1970-01-01
    • 2015-12-06
    相关资源
    最近更新 更多