简体   繁体   English

使用php使用JSON编码来卷曲API请求

[英]Curl API request with JSON encoding using php

How to call the following Curl API request using php ? 如何使用php调用以下Curl API请求?

curl "https://api.example.com/v2/test" \
  -X "POST" \
  -H "App-Id: APP_ID" -H "App-Key: APP_KEY" \
  -H "Content-Type: application/json" -d '{
    "sex": "male",
    "age": 30,
    "evidence": [
      {"id": "s_1193", "choice_id": "present"},
      {"id": "s_488", "choice_id": "present"},
      {"id": "s_418", "choice_id": "present"}
    ]
  }'

I could only make it till: 我只能做到:

$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'app_id: '. APP_ID,
    'app_key: '. APP_KEY
));

It is over my head being a newbie. 作为一名新手,这太过头了。 Help requested from experts.. 专家要求的帮助。

I tested this, and it works as you should need: 我对此进行了测试,它可以按照您的需要进行工作:

<?php

define('APP_ID', 'o235oi23h5');
define('APP_KEY', 'o2i3h5oi2h3o5h2o3h5');

$json = '{
    "sex": "male",
    "age": 30,
    "evidence": [
        {"id": "s_1193", "choice_id": "present"},
        {"id": "s_488", "choice_id": "present"},
        {"id": "s_418", "choice_id": "present"}
    ]
}';

//$ch = curl_init('http://localhost.script-library/stacko2.php');
$ch = curl_init('https://api.example.com/v2/test');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',                                                                                
    'Content-Length: ' . strlen($json),
    'app_id: '. APP_ID,
    'app_key: '. APP_KEY
]);                                                                                                                   

$result = curl_exec($ch);

echo '<pre>';
var_dump( $result );
echo '</pre>';

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

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