我想以php流的形式发送帖子请求
$aruguments = http_build_query(
array(
'apikey' => 'xxxxxxxxxxxxxxxxxxxxxxxx',
'appid' => 730,
'min' => 20,
'items_per_page' => 100
)
);
$opts_stream = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-Type: application/json' .
'x-requested-with: XMLHttpRequest',
'content' => $aruguments
)
);
$context_stream = stream_context_create($opts_stream);
$json_stream = file_get_contents('https://api.example.de/Search', false, $context_stream);
$data_stream = json_decode($json_stream, TRUE);
由于某种原因,我收到错误消息:
failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden
如果我使用cUrl发送相同的请求,它可以正常工作,但速度很慢。
这是我的cUrl请求有效
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.example.de/Search');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{ \"apikey\": \"xxxxxxxxxxxxxxxxxxxxxxxxxxxx\",\"min\": 20, \"appid\": 730, \"items_per_page\": $number_of_items_per_request }");
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = 'Accept: application/json';
$headers[] = 'Content-Type: application/json';
$headers[] = 'X-Requested-With: XMLHttpRequest';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
curl_close ($ch);
答案 0 :(得分:1)
已发布的代码存在两个问题。
添加标题时,将它们全部设置在一个字符串中。为了使目标服务器知道一个标头何时结束而另一个标头何时开始,您需要使用新行(\r\n
)将它们分开:
'header' => "Content-Type: application/json\r\n"
. "x-requested-with: XMLHttpRequest\r\n",
您的流上下文和cURL代码之间的最大区别是,您的cURL代码以json格式发布数据,而您的流上下文则以x-www-form-urlencoded字符串发布数据。您仍然在告诉服务器内容是json,所以我觉得服务器有些混乱。
通过更改将数据发布为json,
$aruguments = http_build_query(
array(
'apikey' => 'xxxxxxxxxxxxxxxxxxxxxxxx',
'appid' => 730,
'min' => 20,
'items_per_page' => 100
)
);
到
$aruguments = json_encode(
array(
'apikey' => 'xxxxxxxxxxxxxxxxxxxxxxxx',
'appid' => 730,
'min' => 20,
'items_per_page' => 100
)
);