0

我正在尝试使用 Github v3 API 并发布 JSON 来更新配置文件(或其他调用)并从 Github 获得以下响应;

Array
(
    [message] => Body should be a JSON Hash 
)

我已经浏览了 API Docs 上的相关页面:http: //developer.github.com/v3/users/

这个页面: http: //developer.github.com/v3/#http-verbs涵盖了 POST/PATCH

这是我正在使用的代码

$data = array("bio" => "This is my bio" );
$data_string = json_encode($data); 

function curl($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);  

    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); 
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,1);
    curl_setopt($ch, CURLOPT_USERPWD, "USERNAME:PASSWORD");
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);   
    $content = curl_exec($ch);
    curl_close($ch);
    return $content;
}

$result = json_decode(curl('https://api.github.com/user'),true);

我也尝试CURLOPT_CUSTOMREQUEST'POST''PATCH'但两者都得到了相同的错误响应。

谁能指出我将数据发布到 API 的正确方向?

4

2 回答 2

1

您必须将变量传递给global $data_string或传递给以实现可重用性。$data_stringcurl()

例子:

function curl($curl, $data)
{
    $data_string = json_encode($data);
    // your code here
}
于 2012-05-10T22:10:55.663 回答
0

您应该像这样指定标题:

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 
于 2012-05-10T22:12:41.863 回答