PHP 中 headers 的 curl 请求

curl request with headers in PHP

我想向 URL 发出 cURL 请求以及以下 headers :

'Content-Type: application/json', 'Authorization': 'Basic XXXXXXXXXX'

我有以下代码:

<?php

$post_url = "https://api.interlinkexpress.com/user/?action=login";

$curl = curl_init($post_url);

$headers = array(
        'Content-Type: application/json',
        'Authorization': 'Basic XXXXXXXXX'
        );
//curl_setopt($curl, CURLOPT_USERPWD, "username":"Password");
curl_setopt($curl, CURLOPT_URL, $post_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POST, true);
//curl_setopt($curl, CURLOPT_POSTFIELDS,json_encode($post_data) );
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); 
$post_response = curl_exec($curl); 

?>

结果显示为:

Client sent a Bad Request

这是 $header 数组下的 'Authorization...' 行

任何 suggestions/help 不胜感激。

500 错误通常表明错误在服务器端。您或许可以尝试模拟您的请求(我个人建议使用 Advanced ReST Client,这是一个 google-chrome 应用程序),以验证是否属于这种情况。

问题在 header.It 需要 fixed.authorization 整个字符串会像这样:

$headers = array(
    'Content-Type: application/json',
    'Authorization: Basic XXXXXXXXX'
    );

让我给你一个完整的curl例子:

 function CurlSendPostRequest($url,$request)
    {
        $authentication = base64_encode("username:password");

        $ch = curl_init($url);
        $options = array(
                CURLOPT_RETURNTRANSFER => true,         // return web page
                CURLOPT_HEADER         => false,        // don't return headers
                CURLOPT_FOLLOWLOCATION => false,         // follow redirects
               // CURLOPT_ENCODING       => "utf-8",           // handle all encodings
                CURLOPT_AUTOREFERER    => true,         // set referer on redirect
                CURLOPT_CONNECTTIMEOUT => 20,          // timeout on connect
                CURLOPT_TIMEOUT        => 20,          // timeout on response
                CURLOPT_POST            => 1,            // i am sending post data
                CURLOPT_POSTFIELDS     => $request,    // this are my post vars
                CURLOPT_SSL_VERIFYHOST => 0,            // don't verify ssl
                CURLOPT_SSL_VERIFYPEER => false,        //
                CURLOPT_VERBOSE        => 1,
                CURLOPT_HTTPHEADER     => array(
                    "Authorization: Basic $authentication",
                    "Content-Type: application/json"
                )

        );

        curl_setopt_array($ch,$options);
        $data = curl_exec($ch);
        $curl_errno = curl_errno($ch);
        $curl_error = curl_error($ch);
        //echo $curl_errno;
        //echo $curl_error;
        curl_close($ch);
        return $data;
    }