【发布时间】:2020-06-25 08:35:11
【问题描述】:
我一直在尝试此链接here 中的一些代码。 这是如何使用flask将android连接到python的部分。代码在服务器中运行良好。当我尝试运行 android 应用程序时,它运行良好,直到我单击“连接到服务器”按钮时,结果总是无法连接。 android studio中没有错误
这是python代码
import flask
app = flask.Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def handle_request():
return "Flask Server & Android are Working Successfully"
app.run(host="0.0.0.0", port=5000, debug=True)
这是python代码中的终端。
* Serving Flask app "flaskcoba1" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
* Restarting with stat
* Debugger is active!
* Debugger PIN: 189-748-501
* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
我尝试使用从 cmd 到我的移动设备的 ping 来测试连接以检查连接,它已经连接。
这是main.activity
package com.example.flaskcoba;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void connectServer(View v){
EditText ipv4AddressView = findViewById(R.id.IPAddress);
String ipv4Address = ipv4AddressView.getText().toString();
EditText portNumberView = findViewById(R.id.portNumber);
String portNumber = portNumberView.getText().toString();
String postUrl= "http://"+ipv4Address+":"+portNumber+"/";
String postBodyText="Hello";
MediaType mediaType = MediaType.parse("text/plain; charset=utf-8");
RequestBody postBody = RequestBody.create(mediaType, postBodyText);
postRequest(postUrl, postBody);
}
public void postRequest(String postUrl, RequestBody postBody) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(postUrl)
.post(postBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
// Cancel the post on failure.
call.cancel();
// In order to access the TextView inside the UI thread, the code is executed inside runOnUiThread()
runOnUiThread(new Runnable() {
@Override
public void run() {
TextView responseText = findViewById(R.id.responseText);
responseText.setText("Failed to Connect to Server");
}
});
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
// In order to access the TextView inside the UI thread, the code is executed inside runOnUiThread()
runOnUiThread(new Runnable() {
@Override
public void run() {
TextView responseText = findViewById(R.id.responseText);
try {
responseText.setText(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
});
}
}
这是布局代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="IPv4 Address" />
<EditText
android:layout_weight="4"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="@+id/IPAddress"
android:text="192.168.1.7" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="Port Number" />
<EditText
android:layout_weight="4"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="@+id/portNumber"
android:text="5000"/>
</LinearLayout>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Connect to Server"
android:onClick="connectServer"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Message from the Server ..."
android:id="@+id/responseText" />
</LinearLayout>
终于在logcat中找到错误
2020-06-29 13:28:46.182 3001-3001/? E/IptablesRestoreController: [iptables debug]iptables-restore execute *filter
-nvx -L tetherctrl_counters
COMMIT
2020-06-29 13:28:46.186 3001-3001/? E/IptablesRestoreController: [iptables debug]iptables-restore execute done, res : 0
2020-06-29 13:28:46.186 3001-3001/? E/IptablesRestoreController: [iptables debug]iptables-restore execute *filter
-nvx -L tetherctrl_counters
COMMIT
2020-06-29 13:28:46.190 3001-3001/? E/IptablesRestoreController: [iptables debug]iptables-restore execute done, res : 0
2020-06-29 13:28:57.283 3287-3768/? E/Watchdog: !@Sync 718 [2020-06-29 13:28:57.283] FD count : 517
2020-06-29 13:31:46.659 3645-4181/? E/ImsAdaptorImpl: setSSACInfo : ImsAdaptorImpl.
2020-06-29 13:31:46.661 3889-4332/? E/EPDG -- SIM0 [RILRECEIVER]: Incorrect EpdgIilIpcMessage IPC Message -- not initialized
2020-06-29 13:31:46.663 3645-4181/? E/ImsAdaptorImpl: setSSACInfo : ImsAdaptorImpl.
2020-06-29 13:31:46.664 3889-4332/? E/EPDG -- SIM0 [RILRECEIVER]: Incorrect EpdgIilIpcMessage IPC Message -- not initialized
2020-06-29 13:31:46.670 3889-4332/? E/EPDG -- SIM0 [RILRECEIVER]: RX [NET_REGIST] -- RESPONSE -- not initialized
请帮我修复错误
【问题讨论】:
-
我们看不到客户端使用的 ip 地址。
-
host="127.0.0.1"我不会将它绑定到本地主机。请尝试使用本地局域网 IP。或者也许 0.0.0.0 对所有人开放。 -
认为 onFailure() 和 onResponse() 中不需要 runOnUiThread()。
-
检查这个答案(stackoverflow.com/a/62535200/12368419)它可能有用
-
客户端使用服务器的ip地址,在android应用中输入。我之前尝试过使用 host="0.0.0.0" ,但是当我在浏览器上查看时,它说“无法访问站点”。因此我使用了 host="127.0.0.1" @blackapps