问题
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