为什么我的POST file_get_contents返回HTTP错误请求?

时间:2016-02-03 16:24:23

标签: php rest post curl file-get-contents

这是我的代码:

$url = 'http://99.99.99.999:12480/rs/AuthorizationSession';
$credentials = 'admin:system';
$base64 = base64_encode($credentials);

// Set header text.
$header =   "Content-type: application/json\r\n" .
            "Accept: application/json\r\n" .
            "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);

我一直在:file_get_contents(http://99.99.99.999:12480/rs/AuthorizationSession): failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request

显然我改变了IP。这适用于GET请求,但不适用于POST。

我认为我的标题或发布数据一定有问题,但我无法弄清楚。

思想?

2 个答案:

答案 0 :(得分:3)

http_build_query()将数组转换为URL编码的查询字符串,如name=john&password=s3cr3t,但您发送的Content-Type标题表示POST数据为JSON。

需要更改请求以反映正确的内容类型(application/x-www-form-urlencoded,或http_build_query应该json_encode()将数据作为JSON发送。

就目前而言,服务器很困惑,你告诉它你正在发送JSON,而是发送一个URL编码的字符串(基本上JSON解析在远程上失败)并生成一个错误的请求。

答案 1 :(得分:0)

如果您的代码使用GET,但POST失败,则听起来目标服务器上位于99.99.99.999:12480的主机可能未配置为接受POST请求。