Подтвердить что ты не робот

PHP cURL, POST JSON

Мне нужно отправить следующий код JSON, но по какой-то причине он не работает. Ниже приведен код, который у меня есть.

$fieldString = "395609399";
//the curl request processor
function processCurlJsonrequest($URL, $fieldString) { //Initiate cURL request and send back the result
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTPHEADERS, array('Content-Type: application/json'));
    curl_setopt($ch, CURLOPT_URL, $URL);
    curl_setopt($ch, CURLOPT_USERAGENT, $this->_agent);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_COOKIEFILE, $this->_cookie_file_path);
    curl_setopt($ch, CURLOPT_COOKIEJAR, $this->_cookie_file_path);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
    curl_setopt($ch, CURLOPT_VERBOSE, TRUE);
    if ($fieldCount) { // in case of post fields present then pass it on
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode("{categoryId: $fieldString}"));
        curl_setopt($ch, CURLOPT_POST, 1);
    }
    $resulta = curl_exec($ch);
    if (curl_errno($ch)) {
        print curl_error($ch);
    } else {
        curl_close($ch);
    }
    return $resulta;
}

Вот функция, которая вызывает запрос cURL:

function get_cat($categoryId, $URL) {
    $fields = array(
        "categoryId" => $categoryId
    );
    $fields_string = $fields;
    return $this->processCurlJsonrequest($URL, $fields_string);
}
4b9b3361

Ответ 1

Бит, который является проблемой:

curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode("{categoryId: $fieldString}"));

CURLOPT_POSTFIELDS будет принимать либо массив параметров, либо строку параметров, закодированную в URL-адресе:

curl_setopt($ch, CURLOPT_POSTFIELDS, array('json'=>json_encode($stuff)));
curl_setopt($ch, CURLOPT_POSTFIELDS, 'json='.urlencode(json_encode($stuff)));

Где json будет имя поля POST (то есть: приведет к доступности $_POST['json']).

Ответ 2

Отправьте текст без кодировки JSON и добавьте этот код заголовка:

curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json; charset=utf-8","Accept:application/json, text/javascript, */*; q=0.01")); 

Ответ 3

В исходном примере рабочий код должен выглядеть следующим образом:

//the curl request processor
function processCurlJsonrequest($URL, $fieldString) { //Initiate cURL request and send back the result
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
    curl_setopt($ch, CURLOPT_URL, $URL);
    curl_setopt($ch, CURLOPT_USERAGENT, $this->_agent);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_COOKIEFILE, $this->_cookie_file_path);
    curl_setopt($ch, CURLOPT_COOKIEJAR, $this->_cookie_file_path);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
    curl_setopt($ch, CURLOPT_VERBOSE, TRUE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array("myJsonData" => "test")));
    curl_setopt($ch, CURLOPT_POST, 1); 
    $resulta = curl_exec($ch);
    if (curl_errno($ch)) {
        print curl_error($ch);
    } else {
        curl_close($ch);
    }
    return $resulta;
}

Ответ 4

У меня возникли проблемы с отправкой JSON через cURL, и проблема заключалась в том, что я явно не задавал длину содержимого в заголовке.

Итак, заголовок должен быть:

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($json)));

Ответ 5

Это довольно просто, убедитесь, что вы установили дополнительный заголовок Content-Type для json, а затем CURLOPT_POSTFIELDS может взять json в виде строки. Не требуется кодирование.