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 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化