PHP – 通过file_get_contents发布JSON
发布时间:2020-12-13 14:00:12 所属栏目:PHP教程 来源:网络整理
导读:我正在尝试将 JSON内容发送到远程REST端点,但是“内容”值在交付时似乎为空.所有其他标题等正在正确接收,并且Web服务使用基于浏览器的测试客户端成功测试. 我在下面指定’content’字段的语法有问题吗? $data = array("username" = "duser","firstname" = "
我正在尝试将
JSON内容发送到远程REST端点,但是“内容”值在交付时似乎为空.所有其他标题等正在正确接收,并且Web服务使用基于浏览器的测试客户端成功测试.
我在下面指定’content’字段的语法有问题吗? $data = array("username" => "duser","firstname" => "Demo","surname" => "User","email" => "example@example.com"); $data_string = json_encode($data); $result = file_get_contents('http://test.com/api/user/create',null,stream_context_create(array( 'http' => array( 'method' => 'POST','header' => array('Content-Type: application/json'."rn" . 'Authorization: username:key'."rn" . 'Content-Length: ' . strlen($data_string) . "rn"),'content' => $data_string) ) )); echo $result;
这是我一直使用的代码,它看起来很相似(虽然这对于x-www-form-urlencoded来说当然是这样).
也许你的用户名:key需要base64_encode’d. function file_post_contents($url,$data,$username = null,$password = null) { $postdata = http_build_query($data); $opts = array('http' => array( 'method' => 'POST','header' => 'Content-type: application/x-www-form-urlencoded','content' => $postdata ) ); if($username && $password) { $opts['http']['header'] = ("Authorization: Basic " . base64_encode("$username:$password")); } $context = stream_context_create($opts); return file_get_contents($url,false,$context); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |