doufunuo4787 2018-09-08 10:54
浏览 1012
已采纳

如何将数据从Python发送到Android App

I'm struggling to send JSON data from Python (in the ip adress of 192.168.2.20/Fetch/Fetch.py as host) to Android. I used to do this in php and it was so easy, all needed to be done was this code:

echo json_encode($thedata);

But Python seems to be very hard at this and I don't have any idea how to do this, web doesn't seem to be helping at all as most tutorials suggest using frameworks. So how can I include the python file in my Android app and get the JSON, WITHOUT USING FLASK.

  • 写回答

1条回答 默认 最新

  • drtj40036 2018-09-08 11:18
    关注

    If you are doing anything useful, apart from playing around with python as an android app backend, you should start looking for standard python frameworks to handle HTTP server operations, like django or flask.

    That being said, there's a small stub that I use to act as a test server for my outgoing requests, which should answer your question. You can set any status code, header or response body by modifying it:

    #!/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("
    ----- Request Start ----->
    ")
            print("request_path :", request_path)
            print("self.headers :", self.headers)
            print("<----- Request End -----
    ")
    
            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("
    ----- Request Start ----->
    ")
            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 -----
    ")
    
            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
    "
                        "Run:
    
    ")
        (options, args) = parser.parse_args()
    
        main()
    

    It will do what you are trying to do, out of box. But remember, I just use it as a dummy stub. So, even if you are just exploring, and if there's an Android app involved, and you need to add even 5-6 of if elses to the above code to do what you are doing, it's better to do things right from the beginning, to avoid a lot of rework in future. Use a framework capable of handling boilerplate stuff for you.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 数学的三元一次方程求解
  • ¥20 iqoo11 如何下载安装工程模式
  • ¥15 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 蓝桥杯单片机第十三届第一场,整点继电器吸合,5s后断开出现了问题