Following this tutorial I manage to get token. How now I use this to token to get tweets from user, for example?
Where should I place this token variable and make API call with retrofit?
twitterApi.postCredentials("client_credentials").enqueue(new Callback<OAuthToken>() {
#Override
public void onResponse(Call<OAuthToken> call, Response<OAuthToken> response) {
token = response.body(); // <---- my token
}
#Override
public void onFailure(Call<OAuthToken> call, Throwable t) {
// fail
}});
You could add it in all requests using interceptors, as descibed here How to use interceptor to add Headers in Retrofit 2.0
Related
Imagine this scenario:
I start a requestA using the Call.enqueue() method, then, before requestA be finished, I start requestB at the same endpoint of requestA. While I'm using Call.enqueue() method, requestB will be executed after requestA? Or enqueue() method is just used to do requests asynchronously?
I search that information at docs and here on StackOverflow but all the information is superficial about this specific method.
Here is my code - this same code is used for both requests:
foolRequest.enqueue(new Callback<Response>() {
#Override
public void onResponse(#NonNull Call<Response> call,
#NonNull retrofit2.Response<Response> response) {
//do something
}
#Override
public void onFailure(#NonNull Call<Response> call,
#NonNull Throwable t) {
//do something
}
});
I think so,
Otherwise, if you implement your own connection client.
By the source code from OkHttpClient, there is a dispatcher class, save all the enqueue API, and it uses queue to save the relative task
synchronized void enqueue(AsyncCall call) {
if (runningAsyncCalls.size() < maxRequests && runningCallsForHost(call) < maxRequestsPerHost) {
runningAsyncCalls.add(call);
executorService().execute(call);
} else {
readyAsyncCalls.add(call);
}
}
Hi I'm working with an API, which returns the login page when the session token is invalid/JSON response if the session is valid. How can I implement this with Retrofit, ie having multiple response types ?
P.S It's an old API and it can't be changed. I'm new to retrofit, I'll be really grateful of your help.
Would post this as comment as it's more a suggestion then actual answer but here it goes:
(If you're completely new to Retrofit leave a comment to explain it in more detail)
You could make your Call return a Response like so:
#GET("login/endpoint")
Call<Response> getLogin();
than you can make the call like this
Call<Response> getLogin = ApiService.getLogin();
getLogin.enqueue(new Callback<Void>() {
#Override
public void onResponse(Call<Response> call, Response<Response> response) {
//here you can access Response.body() and use it to determine wether it's json or html and react accordingly
}
#Override
public void onFailure(Call<Response> call, Throwable t) {
//todo: error message
}
});
note: the Response i've used is from the OkHttp Library.
If this doesn't work you could try to make your own converter which has a check for html/json and adding it in the creation of the retrofit instance. i'm not entirely sure how you can go about with that but this seems to have a general idea: custom converter from futurestudio.
If you need more guidance/clarification please let me know i'll be able to answer later today.
I am implementation for Retrofit on api call using images-upload base64Encode string. it is sending data perfect but Retrofit return response Internal Server Error 500 and i am sending request type is Body custom class. Plz help me what i do.
#Headers("Accept:application/json")
#POST(RestClient.postRegister)
Call<RegisterResp> getRegisterResponse(#Body RequestRegisterVo requestRegisterVo);
Call<RegisterResp> call = MyApplication.getRestClient().getApplicationServices().getRegisterResponse(requestRegisterVo);
call.enqueue(new Callback<RegisterResp>() {
#Override
public void onResponse(Call<RegisterResp> call, Response<RegisterResp> response) {
if (Other.isValidResp(response)) {
// success Log.i(TAG,"Register successfully");
} else {
hideDialog();
}
}
#Override
public void onFailure(Call<RegisterResp> call, Throwable t) {
hideDialog();
showToast(t.getMessage());
}
});
The same issue I had to face it, I got a solution in my case-
there is parameter issue, I was sending parameters in String and at the backend, they required Integer parameters.
You also checkout may be there is the issue with parameters or second reason is the URL issue so check it URL also.
I am implementing Link preview feature like WhatsApp, i.e
Provided any link, fetch all its Html
Crawl through Html, read all information
Display text and images
Jsoup Library
I am successfully able to perform this using Jsoup library
Document doc = Jsoup.connect("http://www.techjuice.pk").userAgent("Mozilla").get();
It returns the html code of the page as a response.
Retrofit Library
Now I wanted to perform the same task using Retrofit
Retrofit retrofit = new Retrofit.Builder()
.build();
API api = retrofit.create(API.class);
Call<ResponseBody> call = api.crawlLink("http://techjuice.pk");
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
API.class
public interface API {
#GET
Call<ResponseBody> crawlLink(#Url String url);
}
Exception
java.lang.IllegalStateException: Base URL required.
Unfortunatelly you can't change URL in Retrofit at Runtime in that way.
Try this tutorial: https://futurestud.io/tutorials/retrofit-2-how-to-change-api-base-url-at-runtime-2
or this answer: Set dynamic base url using Retrofit 2.0 and Dagger 2
It would be great if you share some knowledge with me! Here is my problem - we have an Android app. and a server. For some of the calls the client needs to send a previously obtained token from the server which is legit for a limited amount of time. If it happens that the token is not valid any more, an error is returned from the sever, a new token needs to be obtained and we need to retry the request.
But how can I handle such behavior with Retrofit? Any thoughts?
Thank you in advance!
How about you try and make a request with a callback, if the callback is a failure and the error message is that the token needs to be obtained, then you do a request to get the new token for example:
connectionInterface.getSomeStuff(object, new Callback<ObjectPOJO>() {
#Override
public void success(ObjectPOJO objectPOJO, Response response) {
//success
}
#Override
public void failure(RetrofitError error) {
if (error.getLocalizedMessage().equals("Token expire error")
connectionInterface.getToken();
}
Then in your retrofit getToken callback, if it is a success you will redo the getSomeStuff method and if it is a failure, you let the user know. For example:
connectionInterface.getToken(token, new Callback<token>() {
#Override
public void success(token token, Response response) {
//success and token has been added
//add the token to your request somehow...
connectionInterface.updateToken(token);
connectionInterface.getSomeStuff();
}
#Override
public void failure(RetrofitError error) {
//error let user know
}
Let me know if you have any other question. I think this will be the easiest way of doing it.