尝试连接 JSON 服务器时出现异常

木科内塔

我目前正在开发一个用于家庭作业的 CRUD android 应用程序,我遇到了一个奇怪的问题,这在老师提供的示例中没有发生。

我们正在使用 Docker JSON Server 并向该服务器添加数据,但是当我单击按钮转到活动时出现错误。

接下来我将粘贴 logcat:

在此处输入图片说明

并且是由以下原因引起的: 在此处输入图片说明

接下来,我正在复制导致错误的 Java 类“Cliente”:

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class Cliente {
    private static final String URL = "http://localhost:3000/";
    private static Retrofit retrofit = null;

    public static Retrofit obtenerCliente(){
        if(retrofit == null){
            retrofit = new Retrofit.Builder()
                    .baseUrl(URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }

        return retrofit;
    }
}

然后,ActivityPokemones 上的第 80 行:

retrofit = Cliente.obtenerCliente();

我真的不知道哪个是问题,但我在老师给出的例子中没有那个问题,几乎是复制粘贴。

本阿马尔拉乌夫

情况1

如果您使用模拟器:

The bad news first: this solution only work with the emulator and not with your actual devices.

  1. Start up your emulator (since it could take a while until it is ready)
  2. Start your server at localhost and attach the debugger
  3. Change the API endpoints in your Android code to http://10.0.2.2 (This reroutes the requests from your emulator to your computer’s localhost)
  4. Run the Android app on the emulator and cause the requests you want to debug

This should enable you to catch the incoming request on the localhost server. In my case, this quickly resolved my issue.

Obviously, the use of this method is not limited to debugging. If you are on the train and have no Internet connection, you can use this approach to develop your app anyway.

最后一个提示:如果您使用 GenyMotion 作为模拟器,请使用http://10.0.3.2作为 localhost 重新路由地址。


案例二

您正在使用设备:

如果您想避免使用模拟器,则需要采用不同的方法。但是,此解决方案要求您位于同一 Wi-Fi 网络上:

  1. 将 API 请求端点更改为您计算机的本地 IP 地址,例如http://192.168.0.142
  2. 在您的设备上运行该应用程序

再一次,所有请求都应该针对您计算机上运行的本地主机服务器。

如果您有任何疑问或问题,请告诉我们:@futurestud_io

快乐编码!

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

尝试连接到服务器时,Sshutle连接被拒绝

尝试从Gitea连接到AD服务器时出错

尝试连接到gmail IMAP服务器时出现javax.mail.MessagingException

尝试将MySQL服务器连接到Spring Boot App STS时出现多个错误

尝试SSL连接时服务器强制关闭连接

通过JSON将Android App连接到PHP服务器:套接字异常

Windows的Docker:尝试拉时出现“服务器行为异常”

尝试使用Java在远程服务器中连接HBase时出现连接问题

尝试将Docker容器连接到mongodb时出现异常打开套接字异常

尝试将Pyftpsync连接到端口22上的远程服务器时出现EFOError

我尝试连接到服务器时出现“远程服务器超时”异常

尝试从服务器获取JSON数据时出现一些错误

尝试实现SOAP Web服务时出现异常

连接到服务器时出现hazelcast客户端异常

Red5-尝试连接服务器时出现错误

尝试连接到服务器时算法协商失败

尝试连接到蓝牙服务器时连接被拒绝

尝试连接到我的服务器时使用Alamofire和Swift出现401错误

可疑ip尝试连接服务器

尝试安装pip时出现异常

尝试连接到套接字io / express服务器时出现404错误

错误:连接到服务器时监视器线程中出现异常

尝试删除远程虚拟机上的服务时出现异常

尝试打开 OracleConnectionObject 时出现异常

尝试集线器连接时出现 WebSocket 异常

为什么在尝试使用 AutoMapper 时出现异常?

尝试从 gitpod IDE(ubuntu 服务器)连接到 MySql 数据库时出现套接字异常

通过 jmeter 中的 Pepperbox 采样器连接 kafka 服务器时出现异常

Eureka服务器调用API时出现异常