Reputation: 227
I am currently working on a project and trying to do a POST call. The API documentation says the following
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
My code is:
$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 and sub_type are needed for changing the specific data. I get the following error:
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
What am I doing wrong?
Upvotes: 3
Views: 303
Reputation: 17289
The best way in php to POST is to use curl (http://php.net/manual/ru/function.curl-exec.php)
so in your case you can use example (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);
Upvotes: 0
Reputation: 1937
use 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);
}
Upvotes: 0
Reputation: 1410
You're issue seems to be that you are not authenticated.
If you open this request:
https://jawbone.com/nudge/api/v.1.1/users/@me/mood?title=asd&sub_type=2
on your browser, you will see the details of the error. If you check the headers in the response, you see that the status code is "404 Not Found".
I would suggest you to check the documentation of the API about how to authenticate or maybe switch to a supported API version (as the message of the response is "Unsupported API version 1.1, unless called with an OAuth header").
Upvotes: 4