POST调用无法正常工作

时间:2015-01-25 16:45:16

标签: php html api rest post

我目前正在开发一个项目并尝试进行POST调用。 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);
更改特定数据需要

title和sub_type。 我收到以下错误:

 Warning: file_get_contents(http://...@me/mood): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in C:\wamp\www\main.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

我做错了什么?

3 个答案:

答案 0 :(得分:4)

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

如果您打开此请求:

  

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

在浏览器上

,您将看到错误的详细信息。如果检查响应中的标题,则会看到状态代码为“404 Not Found”。

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

答案 1 :(得分:0)

使用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);
}

答案 2 :(得分:0)

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);
相关问题