PHP file_get_contents()发送POST请求(application/json格式)

文章提供了PHP和Python发送POST请求的代码示例,特别关注Content-Type的设置,包括application/json和application/x-www-form-urlencoded两种格式。在PHP中,使用file_get_contents函数并调整header来适应不同的数据格式。Python部分则使用requests库发送JSON格式的数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、发送格式为Content-Type:application/json

function send_post($url, $post_data) { 
  /*发送application/json格式不要下面这句话(否则报错HTTP request failed! HTTP/1.1 400 Bad Request),发送x-www-form-urlencoded需要。*/
  //$postdata = http_build_query($post_data);
  $postdata = $post_data;
  $options = array(
    'http' => array(
      'method' => 'POST',
      'header' => 'Content-Type:application/json', //注意修改为application/json
      'content' =>  json_encode($postdata,true),
      'timeout' => 15 * 60 // 超时时间(单位:s)
    )
  );
  $context = stream_context_create($options);
  $result = file_get_contents($url, false, $context);
  return $result;
}

经验证,代码有效。之前一直报错:PHP Warning: file_get_contents(http://127.0.0.1:8553/uploads/getResult): failed to open stream: HTTP request failed! HTTP/1.1 400 ,把$postdata = http_build_query($post_data);注释了就好了。

参考:使用file_get_contents()发起post带参请求

2、发送格式为Content-Type:x-www-form-urlencoded

function send_post($url, $post_data) { 
  $postdata = http_build_query($post_data);
  $postdata = $post_data;
  $options = array(
    'http' => array(
      'method' => 'POST',
      'header' => 'Content-Type:application/x-www-form-urlencoded', //
      'content' =>  $postdata,
      'timeout' => 15 * 60 // 超时时间(单位:s)
    )
  );
  $context = stream_context_create($options);
  $result = file_get_contents($url, false, $context);
  return $result;
}

未验证过这段代码的有效性,代码来源于下面这篇文章:

学习路之PHP–php如何发送post请求

3、Python发送post请求(json格式)

# 定义将结果发送给后端的请求
def postData(fileName,result):
    payload = {"fileName":fileName + ".php", "result":result}
    headers = {
        'Content-Type': 'application/json'
    }
    resp = requests.post("http://127.0.0.1:8553/uploads/getResult", headers = headers, json = payload)

结论
1、还是需要 json 工具来处理payload。
2、还是需要headers中有 'Content-Type': 'application/json'

`file_get_contents('php://input')` 是 PHP 中一个常用的函数,用于读取原始的 HTTP 请求体数据。这个函数在处理 POST 请求时特别有用,尤其是当请求的数据不是表单编码(如 `application/x-www-form-urlencoded` 或 `multipart/form-data`)时,比如 JSON 或 XML 数据。 ### 使用场景 1. **处理 JSON 数据**:当客户端发送 JSON 格式的数据时,可以通过 `file_get_contents('php://input')` 获取原始的 JSON 字符串,然后使用 `json_decode` 将其转换为 PHP 对象或数组。 2. **处理 XML 数据**:类似地,当客户端发送 XML 格式的数据时,可以通过这个函数获取原始的 XML 字符串,然后使用 `simplexml_load_string` 或其他 XML 解析库进行解析。 3. **处理二进制数据**:当需要处理上传的二进制数据(如文件上传)时,也可以使用这个函数获取原始的二进制数据。 ### 示例代码 ```php <?php // 获取原始的 HTTP 请求体数据 $rawData = file_get_contents('php://input'); // 假设客户端发送的是 JSON 数据 $data = json_decode($rawData, true); if ($data === null) { // 处理 JSON 解码错误 http_response_code(400); echo json_encode(['error' => 'Invalid JSON']); exit; } // 处理数据 echo json_encode(['status' => 'success', 'data' => $data]); ?> ``` ### 优点 - **灵活性**:可以处理各种格式的数据,而不仅仅是表单数据。 - **性能**:直接读取原始数据,避免了 PHP 自动解析表单数据的开销。 ### 注意事项 - **数据长度**:对于非常大的请求体,读取数据可能会消耗大量内存,需要注意数据长度。 - **安全性**:确保对读取到的数据进行适当的验证和消毒,以防止安全漏洞。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值