学无先后,达者为师

网站首页 PHP其他 正文

PHP通过Http Post请求发送Json对象数据

作者:无涯大者 更新时间: 2022-01-28 PHP其他

PHP调用第三方Java/.Net写好的 Restful Api,其中有些接口,需要在发送 POST请求时,传入对象。

Http中传输对象,最好的表现形式莫过于JSON字符串了,但是作为参数的接收方,又是需要被告知传过来的是JSON!

只要发送一个http Content-Type头信息即可,即 “Content-Type: application/json; charset=utf-8”,参考代码如下:

/**
 * PHP发送Json对象数据
 * @param $url 请求url
 * @param $jsonStr 发送的json字符串
 * @return array
 */
function send_post_json($url, $jsonStr)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length: ' . strlen($jsonStr)
        )
    );
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return array($httpCode, $response);
}

$target = "http://texst.api.cn/api/dev/start";

$postdata=array();
$postdata["token"]="99d710a1f7bc11eab31a00508c";
$postdata["imei"]="868739053737";
$jsonStr = json_encode($postdata);
$result = send_post_json($target,$jsonStr);
var_dump($result);

//Json字符串转换成类对象 即可

原文链接:https://blog.csdn.net/fengqingtao2008/article/details/120564701

栏目分类
最近更新