【问题标题】:How to POST a cUrl request the right way?如何以正确的方式发布 cUrl 请求?
【发布时间】:2020-11-27 00:40:24
【问题描述】:

我正在尝试向name.com API 发布请求并检查PHP 中的域可用性。我真的有一个简单的测试请求。我浏览了他们的文档和 API,我收到的错误似乎没有解决方案。过去有人使用过他们的 API 吗?我做错了什么?

choose_domain.php

if(isset($_POST['domain'])){
    //get domain mae 
    $domain = $_POST['domain'];
    //
    //
    $url = 'https://api.dev.name.com/v4/domains:checkAvailability';
    $fields = array(
                'username' => $username,
                'password' => $password,
                'token' => $name_token,
                'domainNames' => array($domain)
            );
    
    //url-ify the data for the POST
    $fields_string = http_build_query($fields);
    //
    //
    //
    //open connection
    $ch = curl_init();
    //
    //
    //
    //set the url, number of POST vars, POST data
    curl_setopt($ch,CURLOPT_URL, $url);
    curl_setopt($ch,CURLOPT_POST, 1);
    curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
    
    //execute post
    $result_domain = curl_exec($ch);
    
    //close connection
    curl_close($ch);
}

API 响应

{"message":"Unauthenticated"} 

根据他们的API,这个错误意味着以下:

URL 请求有一个尾随句点(name.com 之后的句点)示例: https://api.dev.name.com./v4/domains 。或者,密码已经 输入但未输入用户名,反之亦然。

这根本不是真的,我的代码也不是这样。没有尾随句点。

【问题讨论】:

  • Or, the password has been entered but not the username, or vice versa. 检查 $username 和 $password 包含的内容
  • @Berto99:感谢您的意见。我用'echo $fields_string'检查了网址,一切都在那里。我什至用用户名和密码登录了我的帐户,它正在工作。
  • 请发布回显的内容(obv 模糊的用户名和密码)
  • @Berto99 : $fields_string 回显此username=myusername&password=mypassword&token=mytoken&domainNames%5B0%5D=domain.com
  • 检查https://www.name.com/api-docs/Domains#CheckAvailability domainNames 的数据似乎有误?

标签: php http curl


【解决方案1】:

实际上,您发送的用户名和密码格式错误。 API 端点期望采用 BASICAUTH username and password 的格式,用于在 https://www.name.com/api-docs/Domains#CheckAvailability 中提到的身份验证,但您发送的是原始数据或正文数据。

相反,您必须将username and password 发送为:

curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password); 

所以您的完整代码将如下所示:

if(isset($_POST['domain'])) {
 
    //get domain mae 
    $domain = $_POST['domain'];

    $url = 'https://api.dev.name.com/v4/domains:checkAvailability';
    $fields = array(
                'token' => $name_token,
                'domainNames' => array($domain)
            );
    
    //url-ify the data for the POST
    $fields_string = http_build_query($fields);

    //open connection
    $ch = curl_init();

    //set the url, number of POST vars, POST data
    curl_setopt($ch,CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
    curl_setopt($ch,CURLOPT_POST, 1);
    curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
    
    //execute post
    $result_domain = curl_exec($ch);
    
    //close connection
    curl_close($ch);
} 

【讨论】:

    猜你喜欢
    • 2012-06-24
    • 1970-01-01
    • 2015-12-06
    • 2022-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-01
    • 1970-01-01
    相关资源
    最近更新 更多