无法在cURL请求PHP上解析主机

时间:2016-09-22 11:27:13

标签: php curl ubuntu-16.04

我开始构建我的第一个API,在localhost(Mac OS X El Capitan)上成功测试后,我将其上传到运行Ubuntu 16.04的digitalocean服务器。

我们都尝试从我的localhost和存储API的服务器运行cURL请求,并且两者都返回"无法解析主机"错误编号为6.我的代码:

在API方面

echo "200";exit;

在客户端

$token = 'this is the session token';
$url = "http://xx.xx.xx.xx/API/index.php";
$data = array('username'=>'username','password'=>'password');
$datajson = json_encode($data);

$message = $url . $datajson . 'PUT';
$publishThis = base64_encode(
        hash_hmac('sha256', $message, 'secret key', true)
    );
    $len = 'Content-Length: ' . strlen($message);
$ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, urlencode($url));
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',$len, 'Authorization: ' . $publishThis));
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
    curl_setopt($ch, CURLOPT_POSTFIELDS,$datajson);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, true);
    $response  = curl_exec($ch);
请帮忙!!

P.S:如果我删除urlencode函数,请求大约需要20分钟,并以400错误请求错误结束

1 个答案:

答案 0 :(得分:0)

LATER EDIT:

$token = 'this is the session token';
$url = "http://xx.xx.xx.xx/API/index.php";
$data = array('username'=>'username','password'=>'password');
$datajson = json_encode($data);
$build_query = http_build_query($data);

$message = $url . $datajson . 'PUT';
$publishThis = base64_encode(
        hash_hmac('sha256', $message, 'secret key', true)
);
$len = 'Content-Length: ' . strlen($build_query);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',$len, 'Authorization: ' . $publishThis));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS,$build_query);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
$response  = curl_exec($ch);

if($errno = curl_errno($ch)) {
    $error_message = curl_strerror($errno);
    echo "cURL error ({$errno}):\n {$error_message}";
}   

echo $response;

变化:

$build_query = http_build_query($data);

$len = 'Content-Length: ' . strlen($build_query);

curl_setopt($ch, CURLOPT_POSTFIELDS,$build_query)

CURLOPT_URL

删除网址编码