gpt4 book ai didi

php - 如何将数据从 Python 发送到 Android 应用程序

转载 作者:太空宇宙 更新时间:2023-11-03 13:40:52 26 4
gpt4 key购买 nike

我正在努力将 JSON 数据从 Python(在 192.168.2.20/Fetch/Fetch.py​​ 作为主机的 IP 地址中)发送到 Android。我曾经在 php 中这样做,它非常简单,所有需要做的就是这段代码:

echo json_encode($thedata);

但是 Python 似乎很难做到这一点,我不知道如何做到这一点,网络似乎根本没有帮助,因为大多数教程都建议使用框架。那么如何在不使用 FLASK 的情况下将 python 文件包含在我的 Android 应用程序中并获取 JSON。

最佳答案

如果您正在做任何有用的事情,除了使用 python 作为 android 应用程序后端之外,您应该开始寻找标准的 python 框架来处理 HTTP 服务器操作,例如 django 或 flask。

话虽这么说,但我使用一个小 stub 作为我的传出请求的测试服务器,它应该可以回答您的问题。您可以通过修改来设置任何状态码、 header 或响应正文:

#!/usr/bin/env python
# Reflects the requests with dummy responses from HTTP methods GET, POST, PUT, and DELETE
# Written by Tushar Dwivedi (2017)

import json
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
from optparse import OptionParser

class RequestHandler(BaseHTTPRequestHandler):

def do_GET(self):
request_path = self.path

print("\n----- Request Start ----->\n")
print("request_path :", request_path)
print("self.headers :", self.headers)
print("<----- Request End -----\n")

self.send_response(200)
self.send_header("Set-Cookie", "foo=bar")
self.end_headers()
self.wfile.write(json.dumps({'hello': 'world', 'received': 'ok'}))

def do_POST(self):
request_path = self.path

# print("\n----- Request Start ----->\n")
print("request_path : %s", request_path)

request_headers = self.headers
content_length = request_headers.getheaders('content-length')
length = int(content_length[0]) if content_length else 0

# print("length :", length)

print("request_headers : %s" % request_headers)
print("content : %s" % self.rfile.read(length))
# print("<----- Request End -----\n")

self.send_response(200)
self.send_header("Set-Cookie", "foo=bar")
self.end_headers()
self.wfile.write(json.dumps({'hello': 'world', 'received': 'ok'}))

do_PUT = do_POST
do_DELETE = do_GET


def main():
port = 8082
print('Listening on localhost:%s' % port)
server = HTTPServer(('', port), RequestHandler)
server.serve_forever()


if __name__ == "__main__":
parser = OptionParser()
parser.usage = ("Creates an http-server that will echo out any GET or POST parameters, and respond with dummy data\n"
"Run:\n\n")
(options, args) = parser.parse_args()

main()

它会做你想做的,开箱即用。但请记住,我只是将它用作虚拟 stub 。所以,即使你只是在探索,如果涉及到 Android 应用程序,你甚至需要在上面的代码中添加 5-6 个 if else 来完成你正在做的事情,这会更好从一开始就把事情做对,避免将来有很多返工。使用能够为您处理样板内容的框架。

关于php - 如何将数据从 Python 发送到 Android 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52234591/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com