PHP cURL, POST JSON

后端 未结 5 2154
南方客
南方客 2020-11-28 13:48

I need to POST the following JSON code, but for some reason it is not working. Below is the code that I have.

$fieldString = \"395609399\";
//the curl reques         


        
相关标签:
5条回答
  • 2020-11-28 14:14

    I had issues sending JSON via cURL, and the problem was that I was not explicitly setting the content length in the header.

    So the Header should be:

    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($json)));
    
    0 讨论(0)
  • 2020-11-28 14:21

    Send your text without JSON encoding, and add this header code:

    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json; charset=utf-8","Accept:application/json, text/javascript, */*; q=0.01")); 
    
    0 讨论(0)
  • 2020-11-28 14:23

    The bit that is the problem is:

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

    CURLOPT_POSTFIELDS will accept either an array of parameters, or a URL-encoded string of parameters:

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

    Where json will be the name of the POST field (i.e.: will result in $_POST['json'] being accessible).

    0 讨论(0)
  • 2020-11-28 14:24

    With the initial example, working code should be like this:

    //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;
    }
    
    0 讨论(0)
  • 2020-11-28 14:28

    It's pretty simple really, make sure you've set the extra Content-Type header set for json, and then CURLOPT_POSTFIELDS can take the json as a string. No encoding necessary.

    0 讨论(0)
提交回复
热议问题