为什么从模拟器从android应用程序调用REST API端点时连接失败

问题描述 投票:0回答:2

我正在按照this教程从Andrioa应用程序调用发布函数。服务器在烧瓶上创建。不知道错误即将到来。

我已经尝试在模拟器上运行http // 127.0.0.1:5000来运行应用程序,并尝试了http // [我的IP地址]:5000来在设备上运行android应用程序。但是每次连接失败。

我调试我的项目OnFailure()回调得到调用

任何建议都会有帮助!

我的Android MainActivity.java

package com.asad.testrest;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
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 {
    Button mButton;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mButton = findViewById(R.id.mButton);
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(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);
            }
        });
    }

    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();
                        }
                    }
                });
            }
        });
    }
}

我的Python文件是

import flask

app = flask.Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def handle_request():
    return "Flask Server & Android are Working Successfully"

app.run(port=5000, debug=True)
android rest flask post okhttp
2个回答
0
投票

哪个机器正在运行烧瓶代码?您需要进行设置,以便仿真器可以访问网络以及服务器计算机。

仿真器应该能够看到服务器主机的IP并连接到它。根据您的网络和烧瓶实际运行的位置,您可能需要转发端口或允许通过主机防火墙进行连接。

您是否在本教程中找到了本段?

要确定当前的IPv4地址,请发出ipconfig命令(来自Windows),如下所示。 IPv4地址为192.168.16.110。确保我们将Android手机和开发PC连接到同一网络,这一点非常重要,因为我们使用的是本地IPv4地址。如果它们连接到其他网络,则实验将失败。

尝试从仿真器ping服务器。如果没有响应,则说明连接配置不正确。


0
投票

终于我解决了我的问题。但是要使用ngrok的技术服务。我建议每个面临类似问题的人都必须尝试ngrok

至少观看一个视频并从其文档中查阅,这非常容易!!!!相信我.....

© www.soinside.com 2019 - 2024. All rights reserved.