简体   繁体   English

使用PHP / CURL HTTP POST JSON数组

[英]HTTP POST a JSON array using PHP/CURL

I'm trying to send a JSON array to an API via HTTP POST, get a response and print it. 我正在尝试通过HTTP POST将JSON数组发送到API,获取响应并进行打印。

I tried using cURL to do so, but it doesn't seem to work. 我尝试使用cURL这样做,但是似乎不起作用。 I simply get zero response, a blank page. 我只是得到零响应,空白页。

My request: 我的请求:

<?php
$data = array(
    "login" => "myLogin",
    "password" => "myPassword",
    "id" => "12345",
    "tag" => "test"
    );                                                                    

$json_data = json_encode($data);                                                                                   


$ch = curl_init('URL/api/mylogin');                                                                      
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
'Content-Type: application/json',                                                                                
'Content-Length: ' . strlen($json_data))                                                                       
);                                                                                                                   

$output = curl_exec($ch);

$result = json_decode($output);

echo $result;

?>

The response I should be getting: 我应该得到的回应:

{"status": 200, "message": "OK", "login_key": "abcdefh532h235yh"}

any idea why I'm not getting any response? 知道为什么我没有得到任何回应吗?

(this works ok when I manually test it using a test REST client) (当我使用测试REST客户端手动测试它时,此方法正常)

Try this @rani now you can get response. 试试这个@rani,现在您可以获得响应。

    $url = 'URL/api/mylogin';
    $ch = curl_init($url);

 //curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1');
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  // RETURN THE CONTENTS OF THE CALL
 curl_setopt($ch, CURLOPT_HEADER, false);
 curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
 //curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
 curl_setopt($ch, CURLOPT_USERPWD, 'myLogin'.':'.'myPassword'); 
 curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);

 $response = curl_exec($ch);
 curl_close($ch);
 echo $response;

or pass key as a password in CURLOPT_USERPWD . 或在CURLOPT_USERPWD中将密钥作为密码CURLOPT_USERPWD

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

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