繁体   English   中英

PHP流发布请求不起作用,但可以使用curl

[英]PHP stream post request not working, but works with curl

我想以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);

发布的代码有几个问题。

添加标题时,将它们全部设置在一个字符串中。 为了使目标服务器知道一个标头何时结束而另一个标头何时开始,您需要使用换行符( \\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
    )
);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM