简体   繁体   English

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

[英]Cannot call local REST Api from android device

I am trying to call a local REST API from my android device. 我试图从我的Android设备调用本地REST API。 The call works fine from the emulator but I get an error with connection failed when I try from my device. 从模拟器调用工作正常,但是当我从我的设备上尝试时,连接失败时出现错误。

The server from which I try making the call is a Java SpringBoot application. 我尝试进行调用的服务器是Java SpringBoot应用程序。 I have tried to access the URL with the computer IP (from ipconfig) and with the public IP as well. 我试图用计算机IP(来自ipconfig)和公共IP访问URL。 Only he computer IP works for the emulator. 只有他的计算机IP适用于模拟器。 Both the pc and the android device are on the same network so that shouldn't be a problem. PC和Android设备都在同一个网络上,所以这应该不是问题。

The code from android client side: 来自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);
}

Where ip is my PC's ip. 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];
    }

I'm expecting a successful login call to the server with a LoginResponseDto returned and a homepage activity starting.Instead, when calling loginCall.execute() I get: 我希望通过LoginResponseDto返回并且主页活动开始成功登录服务器。相反,当调用loginCall.execute()时,我得到:

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

I don't what who's is some_ip. 我不知道谁是some_ip。

So, I have solved this by making the port to which tomcat deploys the app public. 所以,我通过将tomcat部署应用程序的端口公开来解决这个问题。 You can do that by entering windows firewall and adding a new inbound rule for that port(usually 8080 or 8081). 您可以通过输入Windows防火墙并为该端口添加新的入站规则(通常为8080或8081)来实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM