doufangmu9087 2014-10-24 19:42
浏览 249

PHP HTTP post - 400 Bad Request

I'm not a PHP programmer by trade, but am in a bind having to code a PHP script that will send an HTTP POST request to an API. This post also includes some JSON content (which I've verified is correctly formatted using jsonlint.com). I'm continually getting "400 Bad Request" so I'm assuming I have something formatted incorrectly.

$json = "<JSON markup goes here>";

$options = array(
    'http' => array
    (
        'method'  => 'POST',
        'content' => $json,
        'header'  =>    "Content-Type: application/json
" .
                "Accept: application/json
" .
                "Api-User: <API USER GOES HERE>
" .
                "Api-Key: <API KEY GOES HERE>
"
    )
);

$url = "https://url/paths";

$context  = stream_context_create( $options );
$result   = file_get_contents( $url, false, $context );
$response = json_decode( $result );

I've searched this site and most of the examples seem to match up with what I'm doing...so I'm at a loss as to what the problem is. The one difference I noticed (vs. the examples) is that mine is posting to an HTTPS url...but from what I've read, that doesn't really make much of a difference. Any help you guys can provide would be greatly appreciated!

  • 写回答

3条回答 默认 最新

  • duaiwu8385 2014-10-24 19:51
    关注

    I don't see any "host" header. Not including the "host" could result in a Bad Request.

    For instance:

    POST http://localhost:8080/api/myService HTTP/1.1
    Host: http://localhost:8080
    Content-Type: application/json
    
    {
        "id" : "value"
    }
    

    Also, all of the examples in the doc use fopen instead of file_get_contents. See http://php.net/manual/en/function.stream-context-create.php

    Edit: Here's an example...

    $options = array(
        'http' => array
        (
            'method'  => 'POST',
            'content' => $json,
            'header'  => "Host: http://localhost:8080
    " .
                    "Content-Type: application/json
    " .
                    "Accept: application/json
    " .
                    "Api-User: <API USER GOES HERE>
    " .
                    "Api-Key: <API KEY GOES HERE>
    "
        )
    );
    
    $url = "http://localhost:8080/api/myService";
    
    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP