![](/img/trans.png)
[英]I wouldn't be able to connect to the Api Rest (made in python Flask Localhost) from my cell phone
[英]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.