使用Google API和cURL发出批量请求 - 不断收到400个错误请求 - 这是我的代码:

时间:2015-04-21 10:36:37

标签: php google-app-engine curl

出了点问题。我一直收到400 Bad Request但似乎无法获得任何其他错误消息。这是代码:

$locations = array("LAX", "LGW");
$dateOut = '2015-04-25';
$dateIn = '2015-04-29';
$passengers = 1;
$destinations = array("NYC","LAX","CHI","WAS","LAS","SFO","MIA","BOS","DEN","AUS");

$apiQueries = array();
foreach ($destinations as $destination) {
    foreach ($locations as $origin) {
        $data = array("request" => array(
            "passengers" => array(
            "adultCount" => $passengers
        ),
        "slice" => array(
            array(
                "origin" => $origin,
                "destination" => $destination,
                "date" => $dateOut
            ),
            array(
                "origin" => $destination,
                "destination" => $origin,
                "date" => $dateIn
            )
        ),
        "solutions" => "10"
        ));

        $apiQueries[] = json_encode($data);
    }
}

$batch = '';
$boundary = '--batch_xyzabc';
$i = 0;
foreach ($apiQueries as $data) {
    $batch .= "\n" . $boundary . "\nContent-Type: application/http\n\nGET /qpxExpress/v1/trips/search?key=my-unique-key" . " \n" . $data . "\n";
    $i ++ ;
    if ($i > 48){
        // we need to split the batch by packs of <50. Close this one and create the next one
        $batch .= "\n" . $boundary . "\n";
        $batches[] = $batch;
        $batch = '' ;
        $i=0;
    }
}

// close the current batch pack
if ($i > 0) $batches[] = $batch . "\n" . $boundary . "\n";

for ($i = 0 ; $i < count($batches) ; $i++) {
    $session = curl_init('https://www.googleapis.com/batch');
    curl_setopt($session, CURLOPT_POST, true);
    curl_setopt($session, CURLOPT_HTTPHEADER, array('Host: www.googleapis.com', 'Content-Type: multipart/mixed; boundary=' . $boundary, 'Content-Length: ' . strlen( $batches[$i])));
    curl_setopt($session, CURLOPT_POSTFIELDS, $batches[$i]);
    curl_setopt($session, CURLOPT_HEADER, true);
    curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($session, CURLOPT_VERBOSE, true);
    curl_setopt($session, CURLINFO_HEADER_OUT, true);
    curl_setopt($session, CURLOPT_SSL_VERIFYPEER, false);

    $resp = curl_exec($session);


    echo $resp;exit; // Shows 400 Bad Request message


    $api_response_info = curl_getinfo($session);
    $pack_of_answers = substr($resp, $api_response_info['header_size']);
    curl_close($session);
}

1 个答案:

答案 0 :(得分:1)

使用PHP调用Google API(在App Engine上或不在App Engine上)的最佳方法是使用Google Client Library