简体   繁体   English

如何在PHP中为HTTP发布请求创建有效内容主体

[英]How to create payload body for http post request in PHP

I have to sent an HTTP Post Request with some customized parameters as header and a payload message (JSON) but in this specified case I don't know how to costruct it in PHP. 我必须发送带有某些自定义参数的HTTP Post Request作为标头和有效负载消息(JSON),但在这种指定的情况下,我不知道如何在PHP中构造它。

I've this code: 我有以下代码:

$url = 'https://refered.link.com';

$data = array(?????); // WHAT?

$options = array(
    'http' => array(
        'header'  => "Content-Type: application/json\r\n"."Accept: application/json\r\n "."Authorization: token xxxxxxxx\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data)
    )
);
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) {
    /* Handle error */ 
}
var_dump($result);

I had to send this body payload: 我必须发送此身体有效载荷:

body='{
"request": {
    "branch":"master"
    "message": "Hi there"
}}'

In general, with simple payoad like this $data = array('key1' => 'value1', 'key2' => 'value2'); 通常,像这样的简单payoad $data = array('key1' => 'value1', 'key2' => 'value2'); you do this $data = array('key1' => 'value1', 'key2' => 'value2' ); 你这样做$data = array('key1' => 'value1', 'key2' => 'value2' ); .

But now, is it this: $data = array('request' => array( "branch" => "master", "message" => "Hi there" ) ); 但是现在是这样$data = array('request' => array( "branch" => "master", "message" => "Hi there" ) );$data = array('request' => array( "branch" => "master", "message" => "Hi there" ) ); ?

我现在在手机中,但是我可能会对您制作的数组进行json_encode,看看哪一个看起来像您需要发送的json。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM