how to do a GET request using retrofit2?

帅比萌擦擦* 提交于 2020-02-24 14:09:32

问题


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 interface:

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

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

Can anyone help me where should I have mistaken?

Thanks & Regards.


回答1:


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/"

and in interface

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



回答2:


If you are getting 404 error its not associated with the retrofit, its backend issue. Is that webservice is currently active one? But i found another issue in your request, which is that

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

and in Retrofit interface you have declared

@GET("/users")

So the combined URL will result in

http://192.168.0.103:8080/SpringWithHibernate/users/users

Which is not correct, you should only declare your base url in the string and service names in retrofit interface methods.



来源:https://stackoverflow.com/questions/40880577/how-to-do-a-get-request-using-retrofit2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!