curl 如何使用API V2 Moz HTTP请求

5w9g7ksd  于 2022-11-13  发布在  其他
关注(0)|答案(2)|浏览(190)

我正在尝试连接到Moz API V2,使用HTTP请求文件获取内容功能,但我是新使用这个...你们能帮助我吗?
其文档中的HTPP请求示例:

POST /v2/url_metrics
Host: lsapi.seomoz.com
Content-Length: [length of request payload in bytes]
User-Agent: [user agent string]
Authorization: Basic [credentials]
{
    "targets": ["facebook.com"]
}

下面是我正在尝试的代码:

$url = 'https://lsapi.seomoz.com/v2/url_metrics';
$domains = json_encode(['targets' => 'moz.com']);

$opts = ['http' =>
    [
        'method' => 'POST',
        'header' => 'Content-Type: application/x-www-form-urlencoded\r\n'.
            ("Authorization: Basic " . base64_encode("mozscape-XXXXX:XXXXX")),
        'content-length' => strlen($domains),
        'user-agent' => $_SERVER['HTTP_USER_AGENT'],
        'content' => $domains,
    ]
];

$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);

print_r($result);

以下是文档的链接:https://moz.com/help/links-api/making-calls/url-metrics
当我打印结果时,我什么都没有得到,可能我缺少一些参数...:(
感谢您抽出宝贵时间:)

2q5ifsrm

2q5ifsrm1#

很有可能您只是发出了一个无效的请求,您将内容类型声明为application/x-www-form-urlencoded,但却将数据发送为application/json
您还需要基本的错误处理(例如,在凭据无效的情况下)。
我会这样写:

$url = 'https://lsapi.seomoz.com/v2/url_metrics';
$content = json_encode(['targets' => 'moz.com']);

$opts = ['http' => [
    'method' => 'POST',
    'content' => $content,
    'header' => implode("\r\n", [
        'Authorization: Basic ' . base64_encode("mozscape-XXXXX:XXXXX"),
        'Content-Type: application/json',
        'Content-Length: ' . strlen($content),
        'User-Agent: ' . $_SERVER['HTTP_USER_AGENT'],
    ]),
]];

$stream = fopen($url, 'r', false, stream_context_create($opts));

if (!is_resource($stream)) {
    die('The call failed');
}

// header information as well as meta data
// about the stream
var_dump(stream_get_meta_data($stream));

// actual data
var_dump(stream_get_contents($stream));

// free resources
fclose($stream);

老实说,sockets & fopen的级别很低,最好使用抽象层:例如Guzzle

omqzjyyz

omqzjyyz2#

对不起,我忘了在这里张贴之前的解决方案...
也许有人正在寻找如何使用moz API V2与PHP...

$username='Access ID';
$password='Secret Key';
$URL='https://lsapi.seomoz.com/v2/url_metrics';
$payload = json_encode(array("targets" => ["moz.com"]));

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$URL);
curl_setopt($ch, CURLOPT_TIMEOUT, 30); //timeout after 30 seconds
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
$result=curl_exec ($ch);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);   //get status code
curl_close ($ch);

print_r(json_decode($result, true));

相关问题