【问题标题】:How to send data from Python to Android App如何将数据从 Python 发送到 Android 应用程序
【发布时间】:2019-02-13 12:27:02
【问题描述】:

我正在努力将 JSON 数据从 Python(在 192.168.2.20/Fetch/Fetch.py​​ 作为主机的 IP 地址)发送到 Android。我以前在 php 中执行此操作,非常简单,只需以下代码即可:

echo json_encode($thedata);

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

【问题讨论】:

  • @ShakibKarami 您提到的问题涉及使用 python 向服务器发送 HTTP 请求。这是关于从服务器端接收 HTTP 请求和发送响应。
  • @Tushar 是的,谢谢我删除了

标签: php android python json


【解决方案1】:

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

话虽如此,我使用一个小存根作为我的传出请求的测试服务器,它应该可以回答您的问题。您可以通过修改设置任何状态码、标头或响应正文:

#!/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()

它会做你想做的事,开箱即用。但请记住,我只是将它用作虚拟存根。所以,即使你只是在探索,并且如果涉及到一个 Android 应用程序,并且你需要在上面的代码中添加 5-6 个 if elses 来做你正在做的事情,最好从一开始是为了避免以后的大量返工。使用能够为您处理样板文件的框架。

【讨论】:

    猜你喜欢
    • 2020-12-18
    • 2021-12-15
    • 2013-02-13
    • 1970-01-01
    • 2015-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多