开机自检呼叫无法正常工作



我目前正在做一个项目,并试图做一个开机自检电话。API 文档说明以下内容

POST https://jawbone.com/nudge/api/v.1.1/users/@me/mood HTTP/1.1
Host: jawbone.com
Content-Type: application/x-www-form-urlencoded
title=MoodTest&sub_type=2

我的代码是:

$url = "http://jawbone.com/nudge/api/v.1.1/users/@me/mood";
$data = array('title' => 'moodTest', 'sub_type' => 2);
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
           'header'  => "Content-type: application/x-www-form-urlencoded",
           'method'  => 'POST',
           'content' => http_build_query($data)
       ),
);
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);

更改特定数据需要标题和sub_type。我收到以下错误:

 Warning: file_get_contents(http://...@me/mood): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in C:wampwwwmain.php on line 53
Call Stack
#   Time    Memory  Function    Location
1   0.0028  265776  {main}( )   ..main.php:0
2   0.9006  268584  postMood( ) ..main.php:15
3   0.9007  271680  file_get_contents ( )   ..main.php:53

我做错了什么?

您的问题似乎是您没有经过身份验证。

如果打开此请求:

https://jawbone.com/nudge/api/v.1.1/users/@me/mood?title=asd&sub_type=2

在浏览器上,您将看到错误的详细信息。如果检查响应中的标头,则会看到状态代码为"404 未找到"。

我建议您查看 API 的文档,了解如何进行身份验证或切换到受支持的 API 版本(因为响应的消息是"不支持的 API 版本 1.1,除非使用 OAuth 标头调用")。

使用javascript:

function getJson() {
            var xhr = new XMLHttpRequest();
            xhr.open("get", "https://jawbone.com/nudge/api/v.1.1/users/@me/mood", true);
            xhr.onload = function(){
                var response = JSON.parse(xhr.responseText);
            }
            xhr.send(null);
}

php 到 POST 的最佳方法是使用 curl (http://php.net/manual/ru/function.curl-exec.php)

因此,在您的情况下,您可以使用示例(http://php.net/manual/ru/function.curl-exec.php#98628):

function curl_post($url, array $post = NULL, array $options = array()) 
{ 
    $defaults = array( 
        CURLOPT_POST => 1, 
        CURLOPT_HEADER => 0, 
        CURLOPT_URL => $url, 
        CURLOPT_FRESH_CONNECT => 1, 
        CURLOPT_RETURNTRANSFER => 1, 
        CURLOPT_FORBID_REUSE => 1, 
        CURLOPT_TIMEOUT => 4, 
        CURLOPT_POSTFIELDS => http_build_query($post) 
    ); 
    $ch = curl_init(); 
    curl_setopt_array($ch, ($options + $defaults)); 
    if( ! $result = curl_exec($ch)) 
    { 
        trigger_error(curl_error($ch)); 
    } 
    curl_close($ch); 
    return $result; 
} 
$url = "http://jawbone.com/nudge/api/v.1.1/users/@me/mood";
$data = array('title' => 'moodTest', 'sub_type' => 2);
$result = curl_post($url, $data);

最新更新