使用PHP的JSON API

时间:2016-09-21 06:01:32

标签: php json api curl

我正在尝试使用PHP使用JSON API。

我尝试使用CURL获得回复:

curl 'http://104.239.130.176:3000/api/users/authenticate?email=my_username_here&password=my_password'

这不会在终端给我任何回应。

我也尝试过使用用户名发送电子邮件:

curl 'http://104.239.130.176:3000/api/users/authenticate?username=my_username_here&password=my_password'

我在PHP文件中写了以下内容,但这在浏览器中给出了404错误。

<?php   
  // Parameters
  $tpm_base_url = 'http://104.239.176.130:3000/'; // ending with /
  $req_uri = 'api/users/authenticate'; // GET /passwords.json
  $username = 'my_username';
  $password = 'my_password';

  // Request headers
  $headers = array( 
    'Content-Type: application/json; charset=utf-8'
  );

  // Request
  $ch = curl_init($tpm_base_url . $req_uri);
  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  curl_setopt($ch, CURLOPT_HEADER, TRUE); // Includes the header in the output
  curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password); // HTTP Basic Authentication
  $result = curl_exec($ch); 
  $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);  
  curl_close($ch);

  // Get headers and body
  list($headers, $body) = explode("\r\n\r\n", $result, 2);
  $arr_headers = explode("\r\n", $headers);
  $arr_body = json_decode($body, TRUE);

  // Show status and array of passwords
  echo 'Status: ' . $status . '<br/>';
  print_r($arr_body);

我不确定我在哪里出错了。 API开发人员的说明如下:

API具有基本的JWT安全性,因此首先请求令牌。

POST请求: http://104.239.176.130:3000/api/users/authenticate

2 个答案:

答案 0 :(得分:1)

curl -H "Accept: application/json" -H "Content-Type: application/json" --data "username=my_username_here&password=my_password" http://104.239.176.130:3000/api/users/authenticate

在终端试试这个,看看你是否有任何反应

在php中使用CURLOPT_POSTFIELDS而不是CURLOPT_USERPWD来发送用户/传递

答案 1 :(得分:0)

试试这个

 $ch = curl_init($tpm_base_url . $req_uri);
 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  curl_setopt($ch, CURLOPT_HEADER, TRUE); // Includes the header in the output
    curl_setopt($ch, CURLOPT_POST, 1);
   curl_setopt($ch, CURLOPT_POSTFIELDS,
            "email=$username&password=$password");
 $result = curl_exec($ch); 
  $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);  
  curl_close($ch);