1

我正在尝试发出 POST 请求并在 API 调用的正文中发送一些值。在API 的文档中,它说我需要发出一个 POST 请求,将startUrls其用作带有keyand的数组value

<?php
$url = 'https://api.apify.com/v1/USERID/crawlers/CRAWLERID/execute?token=TOKENID';

$postData = array(
'startUrls' => array(array('key'=>'START', 'value'=>'https://instagram.com/instagram'))
);
$context = stream_context_create(array(
    'http' => array(
        'method' => 'POST',
        'header' => 'Content-type: application/json',
        'body' => json_encode($postData)
        )
));
$resp = file_get_contents($url, FALSE, $context);
print_r($resp); 
?>

JSON 似乎是它应该的样子,但脚本没有将正文正确发送到网站。

4

2 回答 2

2

根据文档,HTTP 上下文没有body选项。请尝试content

<?php
$url = "https://api.apify.com/v1/USERID/crawlers/CRAWLERID/execute?token=TOKENID";

$postData = [
    "startUrls" => [
        ["key"=>"START", "value" => "https://instagram.com/instagram"]
    ]
];

$context = stream_context_create([
    "http" => [
        "method"  => "POST",
        "header"  => "Content-type: application/json",
        "content" => json_encode($postData)
    ]
]);
$resp = file_get_contents($url, FALSE, $context);
print_r($resp);
于 2018-04-06T21:50:20.527 回答
1

以下代码将起作用。我已经设置了标题并指定了内容类型。

$request = new HttpRequest();
$request->setUrl('$url = 'https://api.apify.com/v1/USERID/crawlers/CRAWLERID/execute?token=TOKENID');
$request->setMethod(HTTP_METH_POST);

$request->setHeaders(array(
  'cache-control' => 'no-cache',
  'content-type' => 'application/x-www-form-urlencoded'
));

$request->setContentType('application/x-www-form-urlencoded');
$request->setPostFields(array('key'=>'START', 'value'=>'https://instagram.com/instagram')
));

try {
  $response = $request->send();

  echo $response->getBody();
} catch (HttpException $ex) {
  echo $ex;
}

如果您想尝试使用 cUrl,则以下代码段将起作用。

$curl = curl_init();
$postData = array(
'startUrls' => array(array('key'=>'START', 'value'=>'https://instagram.com/instagram'))
);

        curl_setopt_array($curl, array(
            CURLOPT_URL => "https://api.apify.com/v1/USERID/crawlers/CRAWLERID/execute?token=TOKENID",
            CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_POSTFIELDS => $postData,
                CURLOPT_HTTPHEADER => array(
                    "Cache-Control: no-cache",
                    "content-type: multipart/form-data;"
                ),
            ));

        $response = curl_exec($curl);
        $err = curl_error($curl);
        curl_close($curl);
于 2018-04-06T21:18:53.303 回答