如何使用retrofit2 执行GET 请求? [英] how to do a GET request using retrofit2?

查看:72
本文介绍了如何使用retrofit2 执行GET 请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在本地主机上运行的 restfull 网络服务.我想在该其余 URL 上进行改造 2 GET 请求.

I have a restfull web service which is running on a localhost. I would like to make a retrofit2 GET request on that rest URL.

MainActivity.java

private void requestData() {
        public static final String BASE_URL = "http://192.168.0.103:8080/SpringWithHibernate/users/";
        Toast.makeText(MainActivity.this, "In requestData() :: " + "ddd", Toast.LENGTH_LONG).show();

        Gson gson = new GsonBuilder().create();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();

        GetUserListAPI api = retrofit.create(GetUserListAPI.class);

        api.getUsersList().enqueue(new Callback<List<UserPojo>>() {
            @Override
            public void onResponse(Call<List<UserPojo>> call, Response<List<UserPojo>> response) {
                Log.d("UserList :: ", "Success");
                Log.d("UserList :: ", "Code :: " + response.code());

                user = response.body();

//                Log.d("UserList :: ", "count :: " + user.size());

//                Log.d("UserList :: ", "Result :: " + user.get(1).getUsername());
            }

            @Override
            public void onFailure(Call<List<UserPojo>> call, Throwable t) {
                Log.d("UserList :: ", "Failure");
            }
        });

    }

GetUserListAPI.java 接口:

public interface GetUserListAPI {
    @GET("/users")
    Call<List<UserPojo>> getUsersList();
}

当我调用 requestData() 方法时,我一直收到 response.code() 为 404.

When I make a call to requestData() method I keep getting response.code() as 404.

谁能帮我看错哪里了?

谢谢&问候.

推荐答案

你的 baseurl 最后包含/users.它应该被删除,因为它会被应用程序从 inerface @GET("/users") 接收你的 baseUrl 应该是

Your baseurl contains /users in the end.It should be removed as it will be received by the app from the inerface @GET("/users") Your baseUrl should be

public static final String BASE_URL = "http://192.168.0.103:8080/SpringWithHibernate/"

在界面中

public interface GetUserListAPI {
    @GET("users")
    Call<List<UserPojo>> getUsersList();
}

这篇关于如何使用retrofit2 执行GET 请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆