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);
注释了就好了。
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;
}
未验证过这段代码的有效性,代码来源于下面这篇文章:
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'