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 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图