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'

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐