gpt4 book ai didi

android - 如何在没有本地主机通信的情况下使用 REST API 在 android 客户端和 python-Flask 服务器之间进行连接?

转载 作者:可可西里 更新时间:2023-11-01 17:24:21 33 4
gpt4 key购买 nike

我想构建一个简单的 android 移动应用程序,它将通过 REST API 与 python-Flask 服务器进行通信 -

因此,android 客户端将在我的 Sumsung Galaxy J7 Prime 手机上运行(通过在我的计算机上运行的 android-studio 脚本使用 USB 连接),python-Flask 服务器将在我的计算机上运行(使用运行 python-Flask通过 PyCharm 工作区文件)。

我想做的就是通过常规连接(不是本地主机)在这些客户端和服务器之间传递一条简单的消息。

这是简单的服务器代码:

from flask import Flask
app = Flask(__name__)

@app.route("/RESTfulExample/json/product/get")
def hello():
return "Hello World !!"

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

此代码在我运行此服务器时运行良好,并使用 google chrome URL 输入 URL 地址:http://127.0.0.1:5000/RESTfulExample/json/product/get

当我在 Jave 中运行将此 URL 发送到服务器的脚本(使用本地主机通信)时,它也能正常工作:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class firstJava {

public static void main(String[] args) {

try {

URL url = new URL("http://localhost:5000/RESTfulExample/json/product/get");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");

if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}

BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));

String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}

conn.disconnect();

} catch (MalformedURLException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

}

输出是:

Output from Server .... 

Hello World !!

当我在我的 andriod-studio 项目中使用完全相同的代码时,问题就来了,只是将 IP 地址从本地主机 (127.0.0.1) 更改为我的计算机的 IP (10.0.0.54):

public void buttonClicked (View view){

EditText editText = (EditText) findViewById(R.id.passwordEditText);
try {

URL url = new URL("http://10.0.0.54:5000/RESTfulExample/json/product/get");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");

System.out.println(conn.getResponseCode());
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}

BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));

String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
editText.setText(output);
}

conn.disconnect();

} catch (MalformedURLException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

当我在 android studio 中运行这个脚本时,我手机中的应用程序崩溃了,而在 android-studio 的控制台中,错误行是那些:

I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.owner.firstapp, PID: 25703
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5721)
at android.widget.TextView.performClick(TextView.java:10931)
at android.view.View$PerformClick.run(View.java:22620)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7409)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5721) 
at android.widget.TextView.performClick(TextView.java:10931) 
at android.view.View$PerformClick.run(View.java:22620) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:7409) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) 
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:110)
at libcore.io.IoBridge.connectErrno(IoBridge.java:137)
at libcore.io.IoBridge.connect(IoBridge.java:122)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:452)
at java.net.Socket.connect(Socket.java:884)
at com.android.okhttp.internal.Platform.connectSocket(Platform.java:117)
at com.android.okhttp.internal.http.SocketConnector.connectRawSocket(SocketConnector.java:438)
at com.android.okhttp.internal.http.SocketConnector.connectCleartext(SocketConnector.java:105)
at com.android.okhttp.Connection.connect(Connection.java:1333)
at com.android.okhttp.Connection.connectAndSetOwner(Connection.java:1412)
at com.android.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:131)
at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:485)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:466)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:372)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:476)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:418)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:540)

at com.example.owner.firstapp.MainActivity.buttonClicked(MainActivity.java:44)

at java.lang.reflect.Method.invoke(Native Method) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
at android.view.View.performClick(View.java:5721) 
at android.widget.TextView.performClick(TextView.java:10931) 
at android.view.View$PerformClick.run(View.java:22620) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:7409) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) 
I/Process: Sending signal. PID: 25703 SIG: 9
Application terminated.

如上面的分隔线所示,问题出在第 44 行 - System.out.println(conn.getResponseCode());这意味着,出于某种原因,conn.getResponseCode() 不起作用。

所以我知道当我停止使用本地主机连接并转移到 2 台设备之间的常规连接时会出现问题。我只是不知道如何修复它。

我不知道我会在一个简单的服务器-客户端通信上停留这么多时间。如果有人能帮我解决这个简单的问题,我会很高兴。

非常感谢您,抱歉我的英语不好:)

最佳答案

我知道您几个月前发布了这个,但您是否考虑过在您的 list 文件中启用互联网权限?

关于android - 如何在没有本地主机通信的情况下使用 REST API 在 android 客户端和 python-Flask 服务器之间进行连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49258408/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com