无法从Android设备调用本地REST Api

时间:2019-04-08 18:47:38

标签: java android rest

我正在尝试从我的android设备调用本地REST API。从仿真器进行的调用工作正常,但是从设备尝试连接时出现连接失败错误。

我尝试从中进行呼叫的服务器是Java SpringBoot应用程序。我尝试使用计算机IP(从ipconfig)以及公共IP访问URL。只有他的计算机IP才可用于仿真器。 PC和android设备都在同一网络上,所以应该不会有问题。

来自android客户端的代码:

public interface UserService{

    String BASE_URL = "http://ip:8080/";

    @GET("users/{id}")
    Call<User> getUser(@Path("id") int userId);

    @POST("login")
    Call<LoginResponseDto> login(@Body LoginDto loginDto);

    @POST("users")
    Call<User> register(@Body RegisterDto registerDto);
}

其中ip是我的PC的IP。

public LoginResponseDto login(LoginDto loginDto) throws IOException {
        final LoginResponseDto[] user = {new LoginResponseDto()};
        Call<LoginResponseDto> loginCall = userService.login(loginDto);
        Response<LoginResponseDto> response = loginCall.execute();
        if (response.code() == 401) {
            try {
                JSONObject jObjError = new JSONObject(response.errorBody().string());
                System.out.println("MESSAGE = " + jObjError.getString("message"));
                throw new RuntimeException(jObjError.getString("message"));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        user[0] = response.body();
        return user[0];
    }

我期望成功登录服务器并返回LoginResponseDto并启动主页活动。相反,当调用loginCall.execute()时,我得到:

java.net.SocketTimeoutException: failed to connect to /my_pc_ip (port 8080) from /some_ip (port 45074) after 10000ms.

我不知道谁是some_ip。

1 个答案:

答案 0 :(得分:0)

因此,我已通过公开将Tomcat部署应用程序的端口公开来解决此问题。为此,您可以输入Windows防火墙并为该端口(通常是8080或8081)添加新的入站规则。