使用PHP访问API

使用PHP访问API,php,json,api,curl,Php,Json,Api,Curl,我试图从API访问Json数据。一直在网上做研究,但找不到合适的指导资源。我的文档建议执行以下操作,但是我应该使用什么方法来使用PHP提取这些数据。这就是我目前所拥有的 <?php $header = array(); $header[] = 'Content-type: application/json'; $header[] = 'Authorization: Basic '.base64_encode('MY_TOKEN_HERE'); $url =

我试图从API访问Json数据。一直在网上做研究,但找不到合适的指导资源。我的文档建议执行以下操作,但是我应该使用什么方法来使用PHP提取这些数据。这就是我目前所拥有的

<?php

$header = array();
    $header[] = 'Content-type: application/json';

    $header[] = 'Authorization: Basic '.base64_encode('MY_TOKEN_HERE'); 

    $url = "https://.../v1/StoreServices.svc";

    $ch = curl_init();


            curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);


    $response = curl_exec($ch);
    //echo curl_error($ch);

  if ($response === false){
      echo "Failed";
      throw new Exception(curl_error($ch), curl_errno($ch));
  }
    print_r($response); 
?>
电话样本:

var itemurl = "https://.../Json/Items/";
var token = "<your token here>";
$.ajax({
  type: "GET",
  beforeSend: function(xhr) {
    xhr.setRequestHeader("Authorization", "Basic " + btoa(token));
  },
  url: itemurl,
  dataType: 'json',
  async: false,
  success: function(data, textStatus) { // your actions here }, error:     
  function (xhr, testStatus, errorThrown) { // } });
var itemurl=”https://.../Json/Items/";
var token=“”;
$.ajax({
键入:“获取”,
发送前:函数(xhr){
setRequestHeader(“授权”、“基本”+btoa(令牌));
},
url:itemurl,
数据类型:“json”,
async:false,
成功:函数(数据,文本状态){//此处的操作},错误:
函数(xhr、testStatus、errorshown){/});

看起来后端需要您发送内容长度标题。为此,您需要添加:

$header[] = 'Content-Length: 0';

那是实际的网址吗?不是。这是一个虚拟url。这意味着您的请求现在可以通过应用程序服务器了,祝贺您!检查提供给您的文档,或者询问提供API的人员如何处理此错误,因为这是特定于他们的系统的错误。感谢您的帮助Joni。看起来它起到了作用。我必须在URL的末尾添加/Json/Items/,并更改curl_setopt($ch,CURLOPT_POST,1);到curl_setopt($ch,CURLOPT_GET,1);
$header[] = 'Content-Length: 0';