【问题标题】:Accessing API using PHP使用 PHP 访问 API
【发布时间】:2016-02-22 19:54:30
【问题描述】:

我正在尝试从 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); 
?>

我收到“要求长度 HTTP 错误 411。请求必须分块或具有内容长度。”错误。

我尝试过使用 curl_setopt($ch, CURLOPT_GET, 1);但它会直接将我带到 URL。

我已经用 GET 尝试过,仍然收到错误或端点错误。

https://.../v1/StoreServices.svc/Json/Items/

有什么建议吗?

文档建议将其用于身份验证标头:

var token = "MY_TOKEN_HERE"; $.ajax ({… beforeSend: function (xhr) {   xhr.setRequestHeader("Authorization", "Basic " + btoa(token)); }, …);

和示例调用:

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) { // } });

【问题讨论】:

  • 这是实际的网址吗?
  • 不,不是。这是一个虚拟网址。

标签: php json api curl


【解决方案1】:

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

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

【讨论】:

  • 这意味着您的请求现在正在通过应用程序服务器,恭喜!检查您获得的文档或询问提供 API 的人员如何处理此错误,因为它特定于他们的系统。
  • 感谢乔尼的帮助。
  • 看起来有效。我必须将 /Json/Items/ 添加到末尾或 URL 并更改 curl_setopt($ch, CURLOPT_POST, 1);到 curl_setopt($ch, CURLOPT_GET, 1);
猜你喜欢
  • 2015-08-24
  • 2015-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-23
  • 2021-12-04
  • 2023-04-02
  • 1970-01-01
相关资源
最近更新 更多