【发布时间】: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) { // } });
【问题讨论】:
-
这是实际的网址吗?
-
不,不是。这是一个虚拟网址。