我正在尝试将
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'."\r\n" . 'Authorization: username:key'."\r\n" . 'Content-Length: ' . strlen($data_string) . "\r\n"),'content' => $data_string) ) )); echo $result;
这是我一直使用的代码,它看起来很相似(虽然这对于x-www-form-urlencoded来说当然是这样).
也许你的用户名:key需要base64_encode’d.
原文链接:https://www.f2er.com/php/139490.html也许你的用户名: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); }