简体   繁体   English

使用 PHP cURL POST JSON

[英]POST JSON with PHP cURL

I have the following php code我有以下php代码

curl_setopt($ch, CURLOPT_URL, $URL);
curl_setopt($ch, CURLOPT_USERAGENT, $this->_agent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->_headers);
curl_setopt($ch, CURLOPT_ENCODING , "gzip");
curl_setopt($ch, CURLOPT_VERBOSE, false); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_TIMEOUT,  120);
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_POSTFIELDS, '{"folderId":"1","parameters":{"amount":3,"ascending":false,"offset":0,"sort":"date"}}');
curl_setopt($ch, CURLOPT_POST, 1);

But I don't understand why is not working .但我不明白为什么不起作用。 The API that I'm posting the JSON to says that the parameters were not received .我发布 JSON 的 API 表示未收到参数。 Is there anything wrong in my code ?我的代码有什么问题吗? I think the whole trick is on the JSON parameters... I'm not sure how to send them as I couldn't see any "nave->value" pair with the http analyzer as it usually appears in simple forms ... just that JSON code without any "name".我认为整个技巧都在 JSON 参数上......我不知道如何发送它们,因为我看不到任何带有 http 分析器的“nave->value”对,因为它通常以简单的形式出现......只是没有任何“名称”的 JSON 代码。

You can try as follows.您可以尝试如下。 Basically if we have a array of data then it should be json encoded using php json_encode .基本上,如果我们有一个数据数组,那么它应该是使用 php json_encode进行json encoded And you should also add content-type in header which can be defined in curl as curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));并且您还应该在header添加content-type ,它可以在 curl 中定义为curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

$data = array("country"=>"US","states"=>array("MHASASAS"=>"MH","XYZABABA"=>"XYZ"));
$postdata = json_encode($data);

$ch = curl_init($URL);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);
curl_close($ch);

you can use this and replace with您可以使用它并替换为

curl_setopt($ch, CURLOPT_POSTFIELDS, '{"folderId":"1","parameters":{"amount":3,"ascending":false,"offset":0,"sort":"date"}}');

use this用这个

$Parameters = array(
    'MerchantCode'        => $MerchantCode,
    'PriceValue'          => $amount,
    'ReturnUrl'           => $callback,
    'InvoiceNumber'       => $resnum,
);

    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($Parameters));

If:you use post method,you should know that:如果:您使用 post 方法,您应该知道:

CURLOPT_POST TRUE to do a regular HTTP POST. CURLOPT_POST TRUE 执行常规 HTTP POST。 This POST is the normal application/x-www-form-urlencoded kind, most commonly used by HTML forms.此 POST 是普通的 application/x-www-form-urlencoded 类型,最常用于 HTML 表单。

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

So:you can do like this:所以:你可以这样做:

$ar_form = array('name'=>'PHPJungle','age'=>66,'gender'=>'male');
$poststr = http_build_query($ar_form ); # important

$options[CURLOPT_HTTPGET] = false;
$options[CURLOPT_POST] = true;
$options[CURLOPT_POSTFIELDS] = $poststr ; //default type:application/x-www-from-urlencoded

curl_setopt_array ( $ch, $options );
# @todo your other codes

This is my class I have used for a long time.The class is based on PHP cURL.这是我用了很久的类。该类基于PHP cURL。 It supports GET/POST,HTTP/HTTPS.支持GET/POST,HTTP/HTTPS。

@see https://github.com/phpjungle/iHttp/ @see https://github.com/phpjungle/iHttp/

You can post a json data with curl like so:您可以像这样使用 curl 发布 json 数据:

Using Command Prompt:使用命令提示符:

    curl -X POST -H "Content-Type: application/json" -d '{"folderId":"1","parameters":{"amount":3,"ascending":false,"offset":0,"sort":"date"}}' $url

Using PHP:使用 PHP:

    $data = array("folderId"=>"1","parameters"=>array("amount"=>3,"ascending"=>false,"offset"=>0,"sort"=>"date"));
    $postdata = json_encode($data);
    OR
    $postdata = '{"folderId":"1","parameters":{"amount":3,"ascending":false,"offset":0,"sort":"date"}}';
    
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
    $result = curl_exec($ch);
    curl_close($ch);

    print_r($result);
$link = "http://test.domain/myquery";
   $json = '{"folderId":"1","parameters":{"amount":3,"ascending":false,"offset":0,"sort":"date"}}';
   $postdata = json_decode($json);
 echo openurl($link, $postdata);

This works as json decode converts a json string into array.这在 json decode 将 json 字符串转换为数组时起作用。

function openurl($url, $postvars = "") {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, '3');
        $content = trim(curl_exec($ch));
        curl_close($ch);
        return $content;
    }

if your API endpoint using body for send request using json data may be you can use Guzzle the doc is here doc .如果您的 API 端点使用 body 发送使用 json 数据的请求可能是您可以使用Guzzle文档在这里doc

use GuzzleHttp\Client;
$client = new Client();
$request = $this->client->post($url,array(
            'content-type' => 'application/json'
    ),array());
$request->setBody($json_data);
$response = $request->send();
return $response;

hope this work.希望这项工作。

You haven't set the content type, so the post data is being sent as form data.您尚未设置内容类型,因此发布数据将作为表单数据发送。 Try setting the content type to application/json.尝试将内容类型设置为 application/json。

If that doesn't work, try wrapping the json string with an array.如果这不起作用,请尝试用数组包装 json 字符串。

I'm not sure, that this is the solution but this works for me when posting json, change the json from我不确定,这是解决方案,但这在发布 json 时对我有用,从

'{"folderId":"1","parameters":{"amount":3,"ascending":false,"offset":0,"sort":"date"}}'

to

"{'folderId':'1','parameters':{'amount':3,'ascending':false,'offset':0,'sort':'date'}}"

The only change i made was the double quotes are now on the outside, that works for me but I'm obviously posting to a different server我所做的唯一改变是双引号现在在外面,这对我有用,但我显然要发布到不同的服务器

Only other help I could offer is to download a network debugging tool such as Fiddler or Charles proxy and monitor the requests sent/received, it could be a case that something else is wrong in your code.我能提供的唯一帮助是下载网络调试工具,例如FiddlerCharles代理并监控发送/接收的请求,这可能是您的代码中出现其他错误的情况。

Hope i helped :)希望我有所帮助:)

You can do it make by steps:您可以通过以下步骤进行制作:

$data = array(
    'folderId'=>"1","parameters"=>array(
        "amount"=>"3","ascending"=>false,"offset"=>0,"sort"=>"date"
    )
);

$data_string = http_build_query($data);

$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($data));
curl_setopt($ch,CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);

$result = json_decode($result,true);

I don't know if you need the header.我不知道你是否需要标题。 I think that by default it is already application/x-www-form-urlencode我认为默认情况下它已经是application/x-www-form-urlencode

If it doesn't work, try changing the $data values in array.如果它不起作用,请尝试更改数组中的$data值。 Think it helps.认为它有帮助。 :) :)

first of all please check the curl http status code首先请检查 curl http 状态码

$http_code= curl_get_info($exec_res,CURL_HTTP_CODE);

then modify this request header set with post header API server add a recorder to log those request info.然后使用 post header API 服务器修改此请求标头集,添加一个记录器来记录这些请求信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM