如何使用PHP的curl请求通过X-HTTP-Method-Override进行POST操作?

5
我正在使用Google Translate API工作,有可能需要发送大量文本进行翻译。在这种情况下,谷歌建议执行以下操作:

如果您想在单个请求中发送更多数据,则还可以使用POST调用API。POST主体中的q参数必须少于5K字符。要使用POST,您必须使用X-HTTP-Method-Override标头告诉Translate API将请求视为GET(使用X-HTTP-Method-Override:GET)。 Google Translate API文档

我知道如何使用CURL进行普通的POST请求:
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($curl);
curl_close($curl);
echo $response;

但是我如何修改标题以使用X-HTTP-Method-Override?

4个回答

6
curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: GET') );

这个对你有用吗?我仍然收到BAD REQUEST的错误信息。 ;( - tofutim

1

http://php.net/manual/en/function.curl-setopt.php

CURLOPT_HTTPHEADER

一个HTTP头字段数组,格式为array('Content-type: text/plain', 'Content-length: 100')

因此,

curl_setopt($curl, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: GET'));

0

这对我来说不够,我需要使用http_build_query来处理我的数组POST数据 完整的示例:

  $param = array(
    'key'    => 'YOUR_API_KEY_HERE',
    'target' => 'en',
    'source' => 'fr',
    "q" => 'text to translate'
    );
    $formData = http_build_query($param);
    $headers = array( "X-HTTP-Method-Override: GET");
    $ch=curl_init();

    curl_setopt($ch, CURLOPT_POST, 1);

    curl_setopt($ch, CURLOPT_POSTFIELDS,$formData);
    curl_setopt($ch, CURLOPT_HTTPHEADER,$headers );
    curl_setopt($ch, CURLOPT_REFERER, 'http://yoursite'); //if you have refere domain restriction for your google API KEY
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL,'https://www.googleapis.com/language/translate/v2');
    $query = curl_exec($ch);
    $info = curl_getInfo($ch);
    $error = curl_error($ch);
    $data  = json_decode($query,true);

    if (!is_array($data) || !array_key_exists('data', $data)) {
     throw new Exception('Unable to find data key');
    }
    if (!array_key_exists('translations', $data['data'])) {
     throw new Exception('Unable to find translations key');
    }
    if (!is_array($data['data']['translations'])) {
     throw new Exception('Expected array for translations');
    }
    foreach ($data['data']['translations'] as $translation) {
     echo $translation['translatedText'];
    }

我在这里找到了帮助 https://phpfreelancedeveloper.wordpress.com/2012/06/11/translating-text-using-the-google-translate-api-and-php-json-and-curl/,希望对你有所帮助。


0

使用CURLOPT_HTTPHEADER选项从字符串数组中添加标头


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接