I have this json data:
{
userID: 'a7664093-502e-4d2b-bf30-25a2b26d6021',
itemKind: 0,
value: 1,
description: 'Saude',
itemID: '03e76d0a-8bab-11e0-8250-000c29b481aa'
}
and I need to post into json url:
http://domain/OnLeagueRest/resources/onleague/Account/CreditAccount
using php how can I send this post request?
You can use CURL for this purpose see the example code:
$url = "your url";
$content = json_encode("your data to be sent");
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ( $status != 201 ) {
die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
}
curl_close($curl);
$response = json_decode($json_response, true);
Without using any external dependency or library:
$options = array(
'http' => array(
'method' => 'POST',
'content' => json_encode( $data ),
'header'=> "Content-Type: application/json\r\n" .
"Accept: application/json\r\n"
)
);
$context = stream_context_create( $options );
$result = file_get_contents( $url, false, $context );
$response = json_decode( $result );
$response is an object. Properties can be accessed as usual, e.g. $response->...
where $data is the array contaning your data:
$data = array(
'userID' => 'a7664093-502e-4d2b-bf30-25a2b26d6021',
'itemKind' => 0,
'value' => 1,
'description' => 'Boa saudaÁ„o.',
'itemID' => '03e76d0a-8bab-11e0-8250-000c29b481aa'
);
Warning: this won't work if the allow_url_fopen setting is set to Off in the php.ini.
If you're developing for WordPress, consider using the provided APIs: https://developer.wordpress.org/plugins/http-api/
Beware that file_get_contents solution doesn't close the connection as it should when a server returns Connection: close in the HTTP header.
CURL solution, on the other hand, terminates the connection so the PHP script is not blocked by waiting for a response.
use CURL luke :) seriously, thats one of the best ways to do it AND you get the response.
Related
I have this json data:
{
userID: 'a7664093-502e-4d2b-bf30-25a2b26d6021',
itemKind: 0,
value: 1,
description: 'Saude',
itemID: '03e76d0a-8bab-11e0-8250-000c29b481aa'
}
and I need to post into json url:
http://domain/OnLeagueRest/resources/onleague/Account/CreditAccount
using php how can I send this post request?
You can use CURL for this purpose see the example code:
$url = "your url";
$content = json_encode("your data to be sent");
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ( $status != 201 ) {
die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
}
curl_close($curl);
$response = json_decode($json_response, true);
Without using any external dependency or library:
$options = array(
'http' => array(
'method' => 'POST',
'content' => json_encode( $data ),
'header'=> "Content-Type: application/json\r\n" .
"Accept: application/json\r\n"
)
);
$context = stream_context_create( $options );
$result = file_get_contents( $url, false, $context );
$response = json_decode( $result );
$response is an object. Properties can be accessed as usual, e.g. $response->...
where $data is the array contaning your data:
$data = array(
'userID' => 'a7664093-502e-4d2b-bf30-25a2b26d6021',
'itemKind' => 0,
'value' => 1,
'description' => 'Boa saudaÁ„o.',
'itemID' => '03e76d0a-8bab-11e0-8250-000c29b481aa'
);
Warning: this won't work if the allow_url_fopen setting is set to Off in the php.ini.
If you're developing for WordPress, consider using the provided APIs: https://developer.wordpress.org/plugins/http-api/
Beware that file_get_contents solution doesn't close the connection as it should when a server returns Connection: close in the HTTP header.
CURL solution, on the other hand, terminates the connection so the PHP script is not blocked by waiting for a response.
use CURL luke :) seriously, thats one of the best ways to do it AND you get the response.
I am trying to use Thycotic PAM API. According to their documentation, The following is a sample HTTP POST request. The placeholders shown need to be replaced with actual values.
POST /SecretServer/webservices/SSWebservice.asmx/GetUser HTTP/1.1
Host: 192.168.3.242
Content-Type: application/x-www-form-urlencoded
Content-Length: length
token=string&userId=string
I can get token string and user ID from the app. With this data, following is the PHP code I am trying
$url = 'https://192.168.3.242/SecretServer/webservices/SSWebservice.asmx/GetUser';
$data = array(
'token' => 'token_string',
'userId' => 8
);
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = json_decode(file_get_contents($url, false, $context));
if ($result === FALSE) { /* Handle error */ }
var_dump($result);
I also tried this way:
function curl_get_contents($url)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$url = 'https://192.168.3.242/SecretServer/webservices/SSWebservice.asmx/GetUser?token=token_string&userId=8 HTTP/1.1';
$json = json_decode(curl_get_contents($url));
var_dump($json);
Both of them are returning nothing. Any suggestion is much appreciated.
curl_setopt($ch ,CURLOPT_POST, 1);
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch ,CURLOPT_POSTFIELDS, "token=string&userId=string");
you must use this parameters
I'm working OAuth connect Yahoo.jp login API
I try sending http request use file_get_contents but It's return errors
Here is my code
// my apps setting
$client_id = 'dj0zaiZpP~~~~~~~~~~~~~~~';
$appSecret = '129ad~~~~~~~~~~~~~~~~';
// the data to send
$data = array(
'grant_type' => 'authorization_code',
'redirect_uri' => 'My_redierct_page',
'code' => $_GET['code']
);
$data = http_build_query($data);
$header = array(
"Authorization: Basic " . base64_encode($client_id . ':' . $appSecret),
"Content-Type: application/x-www-form-urlencoded",
"Content-Length: ".strlen($data)
);
// build your http request
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => implode("\r\n", $header),
'content' => $data,
'timeout' => 10
)
));
// send it
$resp = file_get_contents('https://auth.login.yahoo.co.jp/yconnect/v1/token', false, $context);
$json = json_decode($resp);
echo($json->token_type . " " . $json->access_token);
The result...
file_get_contents(https://auth.login.yahoo.co.jp/yconnect/v1/token): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request in /var/www/html/api/auth_proc2.php on line 33
Here is another error message get using set_error_handler()
file_get_contents(): Content-type not specified assuming application/x-www-form-urlencoded
I can't understand this situation
Because I send Content-type in http header
and allow_url_fopen = on in my php.ini
Please help me~! Thanks.
The other thing I'd suggest using is CURL rather then file_get_contents for multiple reasons; first you'll have a lot more control over the request, second its more standard to use curl requests when dealing with API's, and third you'll be able to see better what your problem is.
Try replacing your code with the following and see what you get.
$client_id = 'dj0zaiZpP~~~~~~~~~~~~~~~';
$appSecret = '129ad~~~~~~~~~~~~~~~~';
$data = array(
'grant_type' => 'authorization_code',
'redirect_uri' => 'My_redierct_page',
'code' => $_GET['code']
);
$curl = curl_init('https://auth.login.yahoo.co.jp/yconnect/v1/token');
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($curl, CURLOPT_USERPWD, $client_id . ':' . $appSecret);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
$info = curl_getinfo($curl);
print_r($response);
echo '<br /><br />';
print_r($info);
curl_close($curl);
I assume its probably because your using Content-Type and not Content-type and Content-Length instead of Content-length.
When I first started, I thought Curl would be an excellent way of retrieving a chunk of data in the format json. It didn't work. I tried doing some Ajax request instead, but that didn't work either.
Now, this is my Curl request:
$ch = curl_init("url");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept' => 'application/json',
'Auth' => 'code',
));
$data = curl_exec($ch);
curl_close($ch);
print_r($data);
... The CURL requests RETURNS a EMPTY STRING. No errors...
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept: application/json\r\n" . "Auth: code",
)
);
$context = stream_context_create($opts);
$url = "";
$fp = fopen($url, 'r', false, $context);
$r = #stream_get_contents($fp);
fclose($fp);
print_r($r);
Provides a nice array with json data. Why? Isn't this literally supposed to do the same thing?
Because CURLOPT_HTTPHEADER doesn't take associated arrays. You need to add the complete header.
$ch = curl_init("url");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept: application/json',
'Auth: code',
));
$data = curl_exec($ch);
curl_close($ch);
print_r($data);
file_get_contents not working for fetching fata from facebook using batch requests.Am using the code below:
$url='https://graph.facebook.com/?batch=[{ "method": "POST", "relative_url":"method/fql.query?query=SELECT+first_name+from+user+where+uid=12345678"}]& access_token=xxxxxxx&method=post';
echo $post = file_get_contents($url,true);
it produces
Warning: file_get_contents(graph.facebook.com/?batch=[{ "method": "POST", "relative_url": "method/fql.query?query=SELECT+first_name+from+user+where+uid=12345"}]&access_to ken=xxxx&method=post): failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in /home/user/workspace/fslo/test.php on line 9
I would say the most likely answer to this is that you need to pass the URL values through urlencode() - particularly the JSON string.
Also, you should be POSTing the data.
Try this code:
NB: I presume you are building the URL from several variables. If you edit the question with your actual code, I will provide a solution using that code
<?php
$baseURL = 'https://graph.facebook.com/';
$requestFields = array (
'batch' => '[{"method":"POST","relative_url":"method/fql.query?query=SELECT+first_name+from+user+where+uid=12345678"}]',
'access_token' => 'whatever'
);
$requestBody = http_build_query($requestFields);
$opts = array(
'http'=>array(
'method' => 'POST',
'header' => "Content-Type: application/x-www-form-urlencoded\r\n"
. "Content-Length: ".strlen($requestBody)."\r\n"
. "Connection: close\r\n",
'content' => $requestBody
)
);
$context = stream_context_create($opts);
$result = file_get_contents($baseURL, FALSE, $context);
A "more standard" way to do this these days is with cURL:
<?php
$baseURL = 'https://graph.facebook.com/';
$requestFields = array (
'batch' => '[{"method":"POST","relative_url":"method/fql.query?query=SELECT+first_name+from+user+where+uid=12345678"}]',
'access_token' => 'whatever'
);
$requestBody = http_build_query($requestFields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $baseURL);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestBody);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded',
'Content-Length: '.strlen($requestBody),
'Connection: close'
));
$post = curl_exec($ch);