doufuxing8691 2016-02-03 16:24
浏览 97
已采纳

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

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?

  • 写回答

2条回答 默认 最新

  • dongyuan1984 2016-02-03 19:44
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog