如何构建通过PHP' cURL

时间:2016-02-16 13:47:38

标签: json curl

我有一个api,当我使用POSTMAN时工作正常,但现在我试图用PHP发送它我得到一个API错误消息作为响应。

  

格式错误:异常消息是'传入的消息具有意外的消息格式' Raw'

我确信这与我的数据结构有关。谁能告诉我哪里出错了?

标题

Connection: Keep-Alive
Content-Type: application/json; charset=utf-8

JSON Body

{
    "accessID": "ASASD22",
    "password": "DASD2DQA",
    "messages": [
        {
            "DestinationID": "22D2D2D22D",
            "UserMessageID": 133,
            "RawPayload": [1,31, 34, 43]
        }
    ]
}

这是我编写的PHP代码,但返回错误代码;你们能看到任何问题吗?

$headers= array('Connection: Keep-Alive','Content-Type: application/json; charset=utf-8','Connection: Keep-Alive'); 

$data = array(
    "accessID" => "ASASD22",
    "password" => "DASD2DQA",
    "messages" =>  array(
    "DestinationID" => "22D2D2D22D",
    "UserMessageID" => "133",
    "RawPayload" => "[1,31, 34, 43]"
    )
);

$url_send ="http://api.SITE.com/RST-MESSAGE.svc/submit.json/";
$str_data = json_encode($data);

function sendPostData($url, $post){
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS,$post);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

echo " " . sendPostData($url_send, $str_data);

2 个答案:

答案 0 :(得分:0)

很难猜到,您应该查看API的文档。

但是,如果数据发布为" JSON Body"是你发送的请求,然后你应该用PHP完全复制它(你不会):

$('time').siblings('.overlay').parents('tr').last();

我对您的数据结构进行了两处更改。请参阅下面$data = array( "accessID" => "ASASD22", "password" => "DASD2DQA", "messages" => array( array( "DestinationID" => "22D2D2D22D", "UserMessageID" => "133", "RawPayload" => array(1, 31, 34, 43), ), ) ); 要求更改JSON body

结构的$data部分
  • "messages": [ { ... } ] - messages是一个对象数组,而不是一个对象;
  • "RawPayload": [1, 31, 34, 43] - RawPayload是一个整数数组,而不是字符串;

答案 1 :(得分:0)

我找到了一种在PHP cURL函数中正确发送整个JSON的方法

<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,            "http://api.SITE.com/Messages.svc/submit.json/" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_POST,           1 );
curl_setopt($ch, CURLOPT_POSTFIELDS,     '{
    "accessID": "ASASD22",
    "password": "DASD2DQA",
    "messages": [
        {
            "DestinationID": "22D2D2D22D",
            "UserMessageID": 133,
            "RawPayload": [1,31, 34, 43]
        }
            ]
    }' );
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json','Content-Type: application/json'));

$result=curl_exec ($ch);

echo $result;
?>

所以基本上我将整个JSON包装到curl_setopt($ch, CURLOPT_POSTFIELDS, $data)并以这种方式发送!