如何将 post 请求从 php 发送到 python?

Posted

技术标签:

【中文标题】如何将 post 请求从 php 发送到 python?【英文标题】:How send post request from php to python? 【发布时间】:2017-08-22 04:59:12 【问题描述】:

我想从 php 发送 post 请求到 python 并得到答案 我写了这个发送帖子的脚本

$url = 'http://localhost:8080/cgi-bin/file.py';
$body = 'hello world';
$options = array('method'=>'POST',
'content'=>$body,
'header'=>'Content-type:application/x-ww-form-urlencoded');
$context = stream_context_create(array('http' => $options));
print file_get_contents($url, false,$context);

我正在使用自定义 python 服务器

from http.server import HTTPServer, CGIHTTPRequestHandler
server_address = ("", 8080)
httpd = HTTPServer(server_address, CGIHTTPRequestHandler)
httpd.serve_forever()

以及接受post请求的python脚本

print('Content-type: text/html\n')
import cgi
form = cgi.FieldStorage()
text2 = form.getfirst("content", "empty")
print("<p>TEXT_2: </p>".format(text2))

然后我得到

write() argument must be str, not bytes\r\n'

如何解决? P.S对不起我的英语不好

【问题讨论】:

您可能想使用cURL [php.net/manual/en/book.curl.php],或者如果您的代码更多地构建到类中(可能在下面有一个框架),那么我会看看GuzzleHttp [ docs.guzzlephp.org/en/latest/]图书馆 这是一个关于如何使用 cURL 的示例 [davidwalsh.name/curl-post] 【参考方案1】:

检查 php 的 curl 扩展 http://php.net/manual/en/book.curl.php

<?php

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,"http://localhost:8080/cgi-bin/file.py");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
        "postvar1=value1&postvar2=value2&postvar3=value3");

// in real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS, 
//          http_build_query(array('postvar1' => 'value1')));

// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$server_output = curl_exec ($ch);

curl_close ($ch);

【讨论】:

【参考方案2】:

您还可以使用像 guzzle 这样的库,其中可能包含您可能想要使用的其他一些花里胡哨的功能。

可以在此处的其他答案中找到示例用法:

https://***.com/a/29601842/6626810

【讨论】:

以上是关于如何将 post 请求从 php 发送到 python?的主要内容,如果未能解决你的问题,请参考以下文章

将 POST 数据从 Android 应用程序发送到 PHP MySQL

如何从 POST 请求中检索 cookie?

PHP cURL无法向api发送POST请求

如何将两个数组作为 POST 请求参数从 AJAX 发送到 MVC 控制器(ASP .NET Core 3.1 剃须刀)?

如何防止用户向 php 文件发送如此多的 post 请求

当我将 var 从 ajax 发送到 php 时,如果 (isset $_Post[]) 不起作用