Here's my code:
$url = 'http://99.99.99.999:12480/rs/AuthorizationSession';
$credentials = 'admin:system';
$base64 = base64_encode($credentials);
// Set header text.
$header = "Content-type: application/json
" .
"Accept: application/json
" .
"RESTAuthorization: " . $base64;
// Set data.
$postdata = http_build_query(
array(
"authorization" => $base64
)
);
// Set options - POST.
$opts = array("http" =>
array(
"method" => "POST",
"header" => $header,
"content" => $postdata
)
);
// Create context and execute.
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
I keep getting: file_get_contents(http://99.99.99.999:12480/rs/AuthorizationSession): failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request
Obviously I changed the IP. This works for a GET request but not POST.
I figure I must have something wrong with my header or post data, but I can't figure it out.
Thoughts?
http_build_query()
converts an array to a URL-encoded query string like name=john&password=s3cr3t
but the Content-Type
header you are sending says the POST data is in JSON.
The request either needs to be changed to reflect the correct Content-Type (application/x-www-form-urlencoded
, or http_build_query
should really be json_encode()
to send the data as JSON.
As it stands now, the server is confused that you are telling it you're sending JSON, but instead sending a URL encoded string (so essentially JSON parsing on the remote is failing) and generating a bad request.
If your code works with GET, but POST fails, it sounds like the host located at 99.99.99.999:12480 on the target server may not be configured to accept POST requests.