正确的使用方法 - > php中的instance_url? (web api)

时间:2015-06-08 09:14:44

标签: php json curl

我需要发送php curl自定义HEADER,以XML或json发布,并在web api中返回响应。搜索,我发现这是尝试用not found requests解决我的问题:

    $ch = curl_init();
LINE 112    curl_setopt($ch, CURLOPT_URL, $urlCall->instance_url . $request);
    ..

参考:

$urlCall = https://ip.andress/v1/requestActivateCode/;

和$ request是一个json params编码(只是测试):

$params = array("RetailTransactionRequest" =>
    array(
        "code" => "0000002381237220",
        "amount" => $amount,
        "upc" => $upc,
        "transactionID" => "1234",
        "dateTime" => $xIncommDateTime,
        "retailerName" => $retailerName
    )
);
$request = json_encode($params);

好的......但结果是:

Notice: Trying to get property of non-object in /home/ubuntu/public_html/ip.adress/public/test.php on line 112
Curl error: Could not resolve host: {"RetailTransactionRequest":{"code":"0000002381237220","amount":"20.00","upc":"799366289999","transactionID":"1234","dateTime":"2015-06-08T09:09

自定义HEADER 的信息是: bool(false)

我需要在服务器API中发布数组并从php文件中的服务器接收答案....为什么不工作?感谢。

1 个答案:

答案 0 :(得分:0)

您的代码存在两个缺陷:

<强>第一

根据您的说法,

$urlCallstring。因此,您无需使用$urlCall->instance_url检索其值。完全使用$urlCall

<强>第二

您不得将JSON字符串附加到您呼叫的网址。您需要使用CURLOPT_POSTFIELDS

因此,您的代码必须如此:

$urlCall = 'https://ip.andress/v1/requestActivateCode/';
$params = array("RetailTransactionRequest" =>
    array(
        "code" => "0000002381237220",
        "amount" => $amount,
        "upc" => $upc,
        "transactionID" => "1234",
        "dateTime" => $xIncommDateTime,
        "retailerName" => $retailerName
    )
);
$request = json_encode($params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $urlCall); // note the use of $urlCall
curl_setopt($ch, CURLOPT_POSTFIELDS, $request); // this passes the JSON string to the server
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json',                                                                                
    'Content-Length: ' . strlen($request))                                                                       
); // this is to tell the server that the request contains JSON