S
S
Sergey Nikolaev2016-03-12 11:55:37
JavaScript
Sergey Nikolaev, 2016-03-12 11:55:37

How to make a POST request to the Yandex Translator API?

The GET request works correctly, the key is fresh and without exceeding the limit, but when trying to make a POST request, the browser, as expected, first makes an OPTIONS request, and for some strange reason, the Yandex api responds to OPTIONS - an empty response with status 403, therefore the POST request is not executed.
With a POST request through, for example, POSTMAN, everything works correctly.
What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Eugene, 2016-03-19
@Eugeny1987

function translate($string)
  {
    $url = 'https://translate.yandex.net/api/v1.5/tr.json/translate?';
    
    $aParams = array();
    $aParams['key'] = 'ключ';
    $aParams['text'] = $string;
    $aParams['lang'] = 'ru-en';
    $aParams['format'] = 'plain';

    $url = $url . http_build_query($aParams);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, 156, 5000);
    curl_setopt($ch, CURLOPT_ENCODING , "");
    $data = curl_exec($ch);
    curl_close($ch);

    if (strlen($data))
    {
      $oData = json_decode($data);

      if (is_object($oData) && $oData->code == 200 && isset($oData->text[0]))
      {
        return $oData->text[0];
      }
    }

    return NULL;
  }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question