【问题标题】:How send post request from php to python?如何将 post 请求从 php 发送到 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对不起我的英语不好

【问题讨论】:

标签: php python


【解决方案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://stackoverflow.com/a/29601842/6626810

    【讨论】:

      猜你喜欢
      • 2020-01-04
      • 2017-03-07
      • 1970-01-01
      • 1970-01-01
      • 2018-10-29
      • 1970-01-01
      • 2017-07-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多