I need to log the request URL that Retrofit creates. I don't find any getter methods on Retrofit object or web interface that is generated via Retrofit. The following is my code, where I want to log the address of every request:
public void onRequestFoods() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Const.BASE_LOCAL)
.addConverterFactory(GsonConverterFactory.create())
.build();
FoodOrderInterface foodInterface = retrofit.create(FoodOrderInterface.class);
Log.d(TAG, "onRequestFoods: request url: ");
foodInterface.listFoods().enqueue(new Callback<FoodResponse>() {
#Override
public void onResponse(Call<FoodResponse> call, Response<FoodResponse> response) {
List<Food> foods = response.body().getBody().getFoods();
mPresenter.onResponse((ArrayList<Food>) foods);
}
#Override
public void onFailure(Call<FoodResponse> call, Throwable t) {
mPresenter.onRequestFailed(t.getMessage());
}
});
}
I think what you need is http logging interceptor the github repo has a straightforward example of how to get it up and running
Related
I want to provide clear code in accordance with the guidelines architecture and CleanCode rules.
I tried to use gson library to serialize data used in retrofit call.
I know that i can use #SerializedName in my model class but i want to learn how to use gson builder.
In MainActivity i have:
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CredentialModel credentials = new CredentialModel("User", "Password");
Gson gson = new GsonBuilder().serializeNulls().create();
String json = gson.toJson(credentials);
UserApiClient userApiClient = RetrofitInstace.getRetrofitInstance().create(UserApiClient.class);
Call<String> call = userApiClient.login(json);
call.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
toastNotify(String.valueOf(response.code()));
}
#Override
public void onFailure(Call<String> call, Throwable t) {
toastNotify("Fail");
}
});
}
});
Interface UserApiClient:
#POST("/api/AppUser/login")
Call<String> login(#Body String credentials);
RetrofitInstance class:
public static Retrofit getRetrofitInstance() {
if (retrofit == null) {
retrofit = new retrofit2.Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(new OkHttpClient())
.build();
}
return retrofit;
}
I receive 400 error code when postman with data coppied from json variable in debug mode to body give me code 200. It isn't my serwer so i can't tell what is done on server side. Also im new in android and don't know how to check raw request in android studio yet.
You're using GsonConverterFactory.create() but you're passing String at Call<String> login(#Body String credentials); . You can't do that.
You need to pass in a POJO that is serialized by gson. Or else retrofit will pass in a null object as the body.
class MyBody {
// serialize it here
}
// You also cannot use a String at Call<String>
// for now use ResponseBody. Create a POJO class later though
Call<ResponseBody> login(#Body MyBody credentials);
What you want to do is already being done inside retrofit.
// retrofit does this for you underneat when you use GsonConverterFactory.create()
Gson gson = new GsonBuilder().serializeNulls().create();
String json = gson.toJson(credentials);
Hi i am using retrofit and rxjava to make a simple request and get the response back but it doesnt seem to be making the request itself or getting the response back?
This is my retrofit code:
public class Controller
public Single<List<ListItems>> getItems() {
return apiCall().getItems();
}
private ServiceCallsApiCall() {
OkHttpClient okHttpClient = new OkHttpClient().newBuilder().addInterceptor(interceptor).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create()).build();
ServiceCallsApiCall serviceCalls= retrofit.create(ServiceCallsApiCall.class);
return foodHygieneServiceCalls;
}
my ServiceCallsApiCall class
#GET("Authorities/basic")
Single<List<ListItems>> getItems();
Here is my Rxjava part of my code that subscribes and observes this
public void getItems() {
new Controller().getItems()
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new SingleObserver<List<ListItems>>() {
#Override
public void onSubscribe(Disposable d) {
Log.d("","onSubscribe");
}
#Override
public void onSuccess(List<ListItems> items) {
viewPresenterCallBacks.updateView(items);
}
#Override
public void onError(Throwable e) {
Log.d("","onError" + e.getMessage());
}
});
}
None of the onSuccess or onError gets called
I had a similar problem recently. The problem is not from retrofit or rxJava, its from the deserialization of the JSON to your ListItem POJO. I believe the crux of the issue is that your JSON deserialization library is unable to translate the Json to POJO.
If you are using Jackson you can just add the #JsonIgnoreProperties(ignoreUnknown = true) to your ListItem class.
In my case I was using GSON and since i wasn't interested in all the JSON properties I just changed my initial retrofit method signature from Single<Movies> getRecentMovies(); to Single<ResponseBody> getRecentMovies(); and extracted the desired fields in my response.
i have a Retrofit service which is calling the following API http://api2.bigoven.com/recipe/1962911?api_key=my_api_key
this is my Retrofit Singleton Interface
public interface RecipeAPI {
String BASE_URL = "http://api2.bigoven.com/";
#GET("recipe/{id}")
Call<Recipe> getRecipe(#Path("id") int ID,
#Query("api_key") String apiKey);
class RecipesFetcher{
private static RecipeAPI service;
public static RecipeAPI getInstance(){
if (service==null) {
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(BASE_URL)
.build();
service = retrofit.create(RecipeAPI.class);
return service;
} else {
return service;
}
}
}
}
this is the Full logcat:
http://codepad.org/lP1AhHCK
this is where i use the Retrofit interface but it always executes onFailure :
RecipeAPI.RecipesFetcher.getInstance().getRecipe(recipeID,API_KEY).enqueue(new Callback<Recipe>() {
#Override
public void onResponse(Call<Recipe> call, Response<Recipe> response) {
if (response.isSuccessful()){
//some code
}
else{
Toast.makeText(RecipeActivity.this, "Something went wrong!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<Recipe> call, Throwable t) {
Toast.makeText(RecipeActivity.this, "Check your Internet Connection!", Toast.LENGTH_SHORT).show();
}
});
}
i tried to get call.toString()
it give me this messageretrofit2.executorcalladapterfactory$executorcallbackcall#428dc288
what is wrong with my code ?
Are you able to provide the endpoint documentation (the contract).
Should you be providing the API key in the header?
If you shouldn't, have you checked that the API key isnt null?
--edit--
Could you change the protocol to https?
The below docs mention that you are required to use https instead of http.
http://api2.bigoven.com/web/documentation/authentication-process
I'm using retrofit 2 to make api call to my server but it get stucked when trying to make api call. This is my code
public interface GOTApi {
#GET("characters.json")
Call<GOTCharacterResponse> getCharacters();
}
Intermediate class to get the data
public class GOTCharacterResponse {
List<GOTCharacter> characters;
}
My class to make api call
public class GOTService {
public static final String BASE_URL = "https://project-8424324399725905479.firebaseio.com/";
public static GOTApi getGOTApi(){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit.create(GOTApi.class);
}
public static void getCharacters(){
getGOTApi().getCharacters().enqueue(new Callback<GOTCharacterResponse>() {
#Override
public void onResponse(Call<GOTCharacterResponse> call, Response<GOTCharacterResponse> response) {
if(response.isSuccessful()){
}
}
#Override
public void onFailure(Call<GOTCharacterResponse> call, Throwable t) {
int a = 0;
}
});
}
}
These are the libraries I'm using
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
compile 'com.squareup.okhttp3:okhttp:3.3.1'
It always get stucked in the getCharacters() method. Of course I have internet permission set in Mainfest.
You may try using Retrofit2 with RxJava, it is more convenient.
public Retrofit providedRetrofit(OkHttpClient okHttpClient){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BuildConfig.BASE_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
return retrofit;
}
Your API interface will look like
public interface Api {
#GET("api/service/schedule/{filial}")
Observable<Response<GOTCharacter>> getSchedule(#Path("some_param") String param);
}
You also need to parse response from JSON. You didn't provided
GOTCharacter class, but you can create code from json response by using
http://www.jsonschema2pojo.org/ service
I think you are implementing wrong onResponse() OR Callback(), because I am using Retrofit 2 too, in which onResponse() looks like this:
#Override
public void onResponse(Response<ListJsonResponseRestaurant> response, Retrofit retrofit) {
...
...
}
I am using Retrofit 2.0 library in my android application by adding it into build.gradle file
// retrofit, gson
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
related code is given below
ApiInterface.java
public interface ApiInterface {
#GET("contacts/")
Call<ContactsModel> getContactsList();
}
ApiClient.java
public class ApiClient {
public static final String BASE_URL = "http://myexamplebaseurl/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
MainActivity.java
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<ContactsModel> call = apiService.getContactsList();
call.enqueue(new Callback<ContactsModel>() {
#Override
public void onResponse(Call<ContactsModel> call, Response<ContactsModel> response) {
if(response.isSuccessful()){
/*here is my data handling*/
}
}
#Override
public void onFailure(Call<ContactsModel> call, Throwable t) {
/*It is the request failure case,
I want to differentiate Request timeout, no internet connection and any other reason behind the request failure
*/
}
});
if we get status code as 4xx or 5xx even though onResponse() will called, so there we need handle that condition also.
Here my question is, How to differentiate reason for request failure i.e onFailure() by using Retrofit 2.0 in Android?
Here my question is, How to differentiate reason for request failure
by using Retrofit 2.0 in Android?
if you have a 4xx or 5xx error, onResponse is still called. There you have to check the response code of the code to check if everything was fine. E.g
if (response.code() < 400) {
in case of No Network connection, onFailure is called. There you could check the instance of the throwable. Typically an IOException