改装弹簧靴无响应

时间:2020-01-16 17:12:41

标签: spring jpa retrofit retrofit2

我在春季启动中有一台服务器,该服务器在端口8080上运行。

现在,我正在尝试使用Retrofit2在Android应用程序中调用rest api。

这是我已经实现的:

        final TextView textView=findViewById(R.id.t1);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://localhost:8080/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        JsonPlaceHolderApi jsonPlaceHolderApi = retrofit.create(JsonPlaceHolderApi.class);

        Call<TC> call = jsonPlaceHolderApi.getPosts();

        call.enqueue(new Callback<TC>() {
            @Override
            public void onResponse(Call<TC> call, Response<TC> response) {
                textView.setText(response.toString());

                if (!response.isSuccessful()) {
                    return;
                }

                TC posts = response.body();
                textView.setText(posts.toString());
            }

            @Override
            public void onFailure(Call<TC> call, Throwable t) {

            }
        });

我可以肯定地说,它不起作用,因为我的api甚至没有被调用。因为Hello World屏幕保持不变。

在我的服务器中,我有记录器,该记录器不记录任何内容,因此不会被调用。

这是我的CORS:

@Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry
                        .addMapping("*")
                        .allowedOrigins("*");
            }
        };
    }

1 个答案:

答案 0 :(得分:0)

问题出在localhost一词上。

出于调试目的,我将android设备与PC连接在一起,因此我的android设备无法连接到localhost,因为它只是我IP地址的别名。

localhost equivalent

为解决此问题,我打开了CMD并写了ipconfig,通过此命令,我可以看到与IP有关的所有详细信息。

在这里它显示我的IPv4地址为$.$.$.$。我只是将localhost替换为$.$.$.$。 现在一切正常。