I humbly come before the people for some much needed assistance with this..
I am using (or trying to use) the skyscanner API - http://partners.api.skyscanner.net/apiservices/pricing/v1.0 as documented here. But I am coming up against this error:
HTTP request failed! HTTP/1.1 411 Length Required
PHP attempt 1
function getSkyScanner() {
$url = 'http://partners.api.skyscanner.net/apiservices/pricing/v1.0?apiKey=MY-API-KEY';
$headers = array( 'Content-Type' => 'application/x-www-form-urlencoded',
'Accept' => 'application/xml');
$contextData = array (
'method' => 'POST',
'header' => $headers);
$context = stream_context_create (array ( 'http' => $contextData ));
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { echo 'error'; }
var_dump($result);
}
My server doesn't support cURL so I'm in need of a solution without it. I'm using localhost with WAMP but I have also tried a live version which comes up with the same error and seemingly same problem. I have tried almost every combination of variables in order to correct the error with a discouraging amount of success (none). This is one such variation including the form contents that I am attempting to send.
PHP attempt 2
function getSkyScanner() {
$url = 'http://partners.api.skyscanner.net/apiservices/pricing/v1.0?apiKey=MY-API-KEY';
$params = array( 'country' => 'GB',
'currency' => 'GBP',
'locale' => 'en-GB',
'originplace' => 'LHR',
'destinationplace' => 'EDI',
'outbounddate' => '2016-10-10',
'adults' => '1'
);
$query = http_build_query($params);
$headers = array( 'Content-Type' => 'application/x-www-form-urlencoded',
'Accept' => 'application/xml');
$contextData = array (
'method' => 'POST',
'header' => $headers,
'content' => $query );
$context = stream_context_create (array ( 'http' => $contextData ));
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { echo 'error'; }
var_dump($result);
}
This throws out:
Content-type not specified
Followed by:
HTTP/1.1 400 Bad Request
If you can help I would appreciate some insight right about now.
Many thanks!
You create headers in a wrong way - instead of an array, headers should be passed as a string.
$headers = "Content-Type: application/x-www-form-urlencoded\r\n" .
"Accept: application/xml\r\n";
You can use below snippet to create the correct request:
function prepare_headers($headers) {
return
implode('', array_map(function($key, $value) {
return "$key: $value\r\n";
}, array_keys($headers), array_values($headers))
);
}
function http_post($url, $data, $ignore_errors = false) {
$data_query = http_build_query($data);
$data_len = strlen($data_query);
$headers = array(
'Content-Type' => 'application/x-www-form-urlencoded',
'Accept' => 'application/xml',
'Content-Length' => $data_len
);
$response =
file_get_contents($url, false, stream_context_create(
array('http' => array(
'method' => 'POST',
'header' => prepare_headers($headers),
'content' => $data_query,
'ignore_errors' => $ignore_errors
)
)
));
return (false === $response) ? false :
array(
'headers' => $http_response_header,
'body' => $response
);
}
Example usage of http_post method:
$result = http_post('http://business.skyscanner.net/apiservices/pricing/v1.0', array(
'apiKey' => 'YOUR_API_KEY',
'country' => 'UK',
'currency' => 'GBP',
'locale' => 'en-GB',
'locationSchema' => 'iata',
'originplace' => 'EDI',
'destinationplace' => 'LHR',
'outbounddate' => '2016-10-10',
'adults' => '1'
), false);
Parameter $ignore_errors in http_post method is reponsible for fetching the content even on failure status codes (400, 500, etc.). If you receive Bad request, set ignore_errors = true -> you'll receive full response from server.
Related
I'm trying send a POST request to my API, with a payload ($data).
$api = new CoindRPC();
$txninfo = $api->gettransaction($argv[1]);
$txinforaw = $api->getrawtransaction($txninfo['txid']);
error_log('=== WALLETNOTIFY ===');
error_log('txninfo: '. print_r($txninfo,true));
$page_containing_sender = file_get_contents('http://redacted.com/api/getrawtransaction?txid=' . $txninfo['txid'] . '&decrypt=1');
$sender_parent_obj = json_decode($page_containing_sender, true);
$possible_senders = $sender_parent_obj['vout'][0]['scriptPubKey']['addresses'];
$encoded_possible_senders = json_encode($possible_senders);
echo json_encode($possible_senders);
$url = 'https://redacted.com/api/register_domain_name';
foreach($txninfo['details'] as $id => $details) {
$data = array(
'txid' => $txninfo['txid'],
'tot_amt' => $txninfo['amount'],
'tot_fee' => $txninfo['fee'],
'confirmations'=> $txninfo['confirmations'],
'comment' => $txninfo['comment'],
'blocktime'=> $txninfo['blocktime'] ? $txninfo['blocktime']:$txninfo['time'],
'account' => $details['account'],
'address' => $details['address'],
'category' => $details['category'],
'amount' => $details['amount'],
'fee' => $details['fee'],
'possible_senders' => $encoded_possible_senders,
);
}
$options = array(
'http' => array(
'header'=> array(
'WWW-Authenticate: Token',
'Authorization: Token [redacted]',
'Accept: application/json',
'Content-type: application/json'
),
'method'=> 'POST',
'content'=> json_encode($data),
),
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
At my API, I get a 500 because, whenever I try to retrieve the POST data, I see that there is none. Does anyone know what's wrong? I'd really appreciate some help. Thanks in advance for any and all help.
What I've tried: changing json_encode to http_build_query, with changing Accept to the appropriate type for http_build_query, and Content-type to the appropriate type for http_build_query.
I have to post some data, but the same adress have some GET and POST functions. My PHP is sending a GET instead of a POST.
$apiURL = 'https://myAPI.com.br/api';
$data = http_build_query(array('postdata' => 10));
$uriRequest = $apiURL.'/main';
$options = array(
"ssl"=>array(
"verify_peer"=>false,
"verify_peer_name"=>false,
),
'https' => array(
'header' => 'Content-type: application/x-www-form-urlencoded',
'method' => 'POST',
'content' => $data
),
);
$context = stream_context_create($options);
$result = file_get_contents($uriRequest, false, $context);
if ($result === FALSE) {
return var_dump($result);
}
return var_dump($result);
I know the ssl part it isnt safe, but it is just for prototyping purpose.
I cant get PHP to POST intestead of GET on the adress 'https://myAPI.com.br/api/main'.
Judging from http://php.net/manual/de/function.stream-context-create.php#74795 the correct way to create a stream context for a https secured page is:
<?php
$context_options = array (
'http' => array (
'method' => 'POST',
'header'=> "Content-type: application/x-www-form-urlencoded\r\n"
. "Content-Length: " . strlen($data) . "\r\n",
'content' => $data
)
);
As you can see we are using 'http' => array... instead of https.
I'm trying to get some json data from another server that needs 3 parameters so that I can access it. I saw this code in internet but its not working. I have searched a lot and I haven't found a solution. When I run this code I get :
use pass and code are missing
(is the response from the server I'm requesting), I hope I made things clear if there's anything I didn't explain please do tell.
$url = 'http://xxxx/.js';
$data =http_build_query(array('user' => 'xx',
'pass' =>'xxx ',
'code' =>'xxx')
);
$options = array(
'http' => array(
'header' => "Content-type: application/json\r\n",
'method' => 'POST',
'content' => $data
)
);
$context= stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { }
echo $result ;
Try to change your payload to json...
$data = json_encode( array(
'user' => 'xxx',
'pass' => 'xxx',
'code' => 'xxx'
) );
and to remove \r\n from your content type
"Content-type: application/json"
I have what I think is correctly written code yet whenever I try and call it I'm getting permission denied from Google.
file_get_contents(https://www.googleapis.com/urlshortener/v1/url): failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden
This isn't a rate limit or anything as I currently have zero ever used...
I would have thought this is due to an incorrect API key but I've tried resetting it a number of times. There isn't some downtime while the API is first applied is there?
Or am I missing a header setting or something else just as small?
public function getShortUrl()
{
$longUrl = "http://example.com/";
$apiKey = "MY REAL KEY IS HERE";
$opts = array(
'http' =>
array(
'method' => 'POST',
'header' => "Content-type: application/json",
'content' => json_encode(array(
'longUrl' => $longUrl,
'key' => $apiKey
))
)
);
$context = stream_context_create($opts);
$result = file_get_contents("https://www.googleapis.com/urlshortener/v1/url", false, $context);
//decode the returned JSON object
return json_decode($result, true);
}
It seems I need to manually specify the key in the URL
$result = file_get_contents("https://www.googleapis.com/urlshortener/v1/url?key=" . $apiKey, false, $context);
This now works. There must be something funny with how the API inspects POST for the key (or lack of doing so).
Edit: For anyone in the future this is my complete function
public static function getShortUrl($link = "http://example.com")
{
define("API_BASE_URL", "https://www.googleapis.com/urlshortener/v1/url?");
define("API_KEY", "PUT YOUR KEY HERE");
// Used for file_get_contents
$fileOpts = array(
'key' => API_KEY,
'fields' => 'id' // We want ONLY the short URL
);
// Used for stream_context_create
$streamOpts = array(
'http' =>
array(
'method' => 'POST',
'header' => [
"Content-type: application/json",
],
'content' => json_encode(array(
'longUrl' => $link,
))
)
);
$context = stream_context_create($streamOpts);
$result = file_get_contents(API_BASE_URL . http_build_query($fileOpts), false, $context);
return json_decode($result, false)->id;
}
I tried to send a post request using this PHP code but throw me 401 Unauthorized error:
$username = 'MyDomain\testuser';
$password = '123456';
$url = 'http://10.20.30.40:8080/TargetPage.aspx';
$data = array(
'username' => $username,
'password' => $password,
'postdata' => 'InputParameter1=Test1&InputParameter2=Test2'
);
$options = array(
'http' => array
(
'method' => 'POST',
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
You're not doing proper basic auth. You have to build the authenticate header yourself:
$options = array(
'http' => array(
'header' => 'Authorization: Basic ' . base64_encode("$username:$password")
)
);
You can't just shove a username/password elements into the array and expect it to work. PHP doesn't know you're building a stream to HTTP basic auth... you have to provide EVERYTHING yourself.