【问题标题】:How can I connect from my Android application to WebApi?如何从我的 Android 应用程序连接到 WebApi?
【发布时间】:2019-08-01 05:17:12
【问题描述】:

我有一个WebApi 应用程序,我将我的数据序列化到PC 的localhost。 我想在我的 Android 应用程序上查看这些数据。我用okhttp3 库编写了一个应用程序。但是它没有用,当我用真实的 url 替换我的 url 时,例如:coindesk 的 api url 运行良好。有趣的是,当我写我的本地主机地址时,它不会抛出任何错误,它只是关闭我手机上的应用程序。这是我的代码:

public class MainActivity extends AppCompatActivity {
private TextView mTextViewResult;
private Button ExecuteButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mTextViewResult = findViewById(R.id.text_wiev_result);
    ExecuteButton = findViewById(R.id.btnCallMethod);

    OkHttpClient client = new OkHttpClient();
    String url = "https://api.coindesk.com/v1/bpi/currentprice.json";
    //String url = "localhost:59085/api/Students";



    ExecuteButton.setOnClickListener(v -> {

        Request request = new Request.Builder()
                .url(url)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(response.isSuccessful())
                {
                    final String myResponse = response.body().string();

                    MainActivity.this.runOnUiThread(() -> mTextViewResult.setText(myResponse));
                }

            }
        });
    });

这是我的 Json 数据:

【问题讨论】:

  • 你能显示localhost:59085/api/Students端点返回的内容吗?
  • 可能您连接的是 3G 而不是无线路由器,因此您无法访问本地主机
  • @MichałZiober 帖子已更新。
  • JSON 看起来是有效的。有什么例外。你也可以显示StackTrace吗?
  • @AntonMakov 它不适用于模拟器。

标签: android json asp.net-web-api deserialization okhttp3


【解决方案1】:

最后我自己解决了我的问题。老实说,有必要通过很多步骤来解决这个问题。我会一步一步讲。

第 1 步: 打开 Windows Defender -> 防火墙和网络保护 -> 通用网络 -> 关闭保护。

步骤:2:安装 Jexus Manager,打开它并转到您电脑名称下的站点选项卡,然后右键单击并添加网站。提供网站名称并在物理路径下选择您的 Web 应用程序路径。给一个端口,例如61508. 主机名使用 127.0.0.1,IP 地址使用您的 IPv4 地址,然后单击确定按钮。

第 3 步: 在左侧单击您的站点名称,然后在打开的区域单击右键,然后转到 -> 管理网站 -> 开始。然后点击管理网站 - > 浏览并检查您的网站是否运行良好。

第 4 步:现在打开 android 并将您的当前 URL 设置为:http://10.0.2.2:61508/api/Students 然后应用程序将正常运行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-18
    • 1970-01-01
    • 2012-12-05
    • 2011-07-12
    • 2021-12-14
    相关资源
    最近更新 更多