我将如何写这个卷曲请求

时间:2012-10-10 12:22:43

标签: php json curl

您好我正在使用API​​。在API文档中,清楚地写出aAll数据是以JSON格式发送和接收的,具有UTF-8编码。之后他们给了一行

$ curl -­-­user name:password https://api.abc.de/erer

我只是想问一下如何按上面提到的方式发送curl请求?用户名和密码将以GETPOSTheaders的形式发送?

我正在使用以下代码但接收空数组。文档说它必须收到一些错误或成功代码。

$ch = curl_init();
            $post_data = array('username'=>$_POST['username'],'password'=>$_POST['password']);
            $post_data = http_build_query($post_data);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
            curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
            curl_setopt($ch, CURLOPT_USERPWD, 'username:password');

            $result = curl_exec($ch);
            curl_close($ch);

            $result = json_decode($result);
            $result = (array) $result;
            echo "<pre>";
            print_r($result);
            echo "</pre>";
            die();

我已打印出curl_get_info的回复

Array
(
[url] => https://api.abc.de/erer
[content_type] => 
[http_code] => 0
[header_size] => 0
[request_size] => 0
[filetime] => -1
[ssl_verify_result] => 0
[redirect_count] => 0
[total_time] => 0
[namelookup_time] => 0.618462
[connect_time] => 0
[pretransfer_time] => 0
[size_upload] => 0
[size_download] => 0
[speed_download] => 0
[speed_upload] => 0
[download_content_length] => 0
[upload_content_length] => 0
[starttransfer_time] => 0
[redirect_time] => 0
)

2 个答案:

答案 0 :(得分:3)

鉴于提供的信息,假设您正在发出POST请求,这样的事情应该有效:

$post_data = http_build_query( $post_array );
$url = 'https://api.abc.de/erer';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, 'name:password');
$data = curl_exec( );
curl_close($ch);

$ post_data应包含key =&gt;的关联数组。要发送的值。 我相信你的用户:密码是在标题中发送的,但PHP.net没有说。

http://www.php.net/manual/en/function.curl-setopt.php

答案 1 :(得分:2)

看看给定的例子..

$token = "username:password";
$url = "https://api.abc.de/erer";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_USERPWD, $token);
/*curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);*/                    
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

if( curl_exec($ch) === false ){
    echo curl_error($ch);
}else{
    $data = curl_exec($ch);
}
curl_close($ch);

echo "<pre>";
print_r($data);
echo "</pre>";