簡體   English   中英

Android Volley似乎無法連接到Flask localhost地址以獲取來自Flask的返回String的GET方法?

[英]Android Volley doesn't seem to be able to connect to Flask localhost address for GET method for return String from Flask?

這是Android Volley代碼:

// I already add the uses-permission for INTERNET to manifest
<uses-permission android:name="android.permission.INTERNET" />

// and add volley to gradle depedencies
compile 'com.android.volley:volley:1.0.0'


StringRequest stringRequest; 
RequestQueue mRequestQueue;  

String url = "http://localhost:5000/bacon"; // This is the localhost to FLask

RequestQueue queue = Volley.newRequestQueue(BaconActivity.this);
stringRequest = new StringRequest(
            Request.Method.GET,
            url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Toast.makeText(BaconActivity.this, response, Toast.LENGTH_SHORT).show();
                    redirectLinkToLogin();
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    Toast.makeText(BaconActivity.this, "That didn't work!", Toast.LENGTH_SHORT).show();
                }
            }
    );

queue.add(stringRequest);

這是Flask代碼:

from flask import Flask, request


app = Flask(__name__)
@app.route('/bacon', methods=['GET', 'POST'])
def bacon():
    if request.method == 'GET':
        return 'You are probably using GET'
    else:
        return 'You are probably using POST'


if __name__ == "__main__":
    app.run(debug=True, host='localhost')

當我運行應用程序時,我的Volley沒有連接到我的Flask(我在運行應用程序之前已經運行了Flask)。 因此,代碼不是檢索返回String,而是每次都運行到Response.ErrorListener。

我正在嘗試從Flask獲取返回String到localhost,並Toast返回String。

 String url = "http://localhost:5000/bacon"; // This is the localhost to FLask 

實際上,沒有。 這是運行設備的本地主機。 無論是模擬器,還是您的物理Android設備。

您可能還需要Flask在host='0.0.0.0'上運行

您需要使用運行Flask的計算機的實際IP。 我相信Android模擬器使用10.0.2.2

我通過進入系統偏好設置>網絡並注意我的IP來解決這個問題。

然后我用這個ip地址重新啟動了我的dev appserver。

dev_appserver.py --host="192.168.1.109" app.yaml

我也在我的JsonObjectRequest聲明中使用了這個相同的ip地址(作為一個Volley請求的一部分。

現在,我可以使用Volley對本地Google端點進行GET調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM