I wanna ask something. So I have an activity to do registration for a new user. The flow for creating an account is that when a user fills the form and sends it to the server, then the server will check the data received whether it's already in the database or not. After that, if the data is new then the user confirmed as successfully registered and the apps will redirect the user to login activity. In this case, the data has been successfully inserted to the database but the logcat show me a line like this:
E/ViewRootImpl: sendUserActionEvent() returned
along with this:
D/EGL_emulation: eglMakeCurrent: 0x9ed852a0: ver 2 0 (tinfo 0x9ed831d0)
E/ERROR :: timeout
also, it didn't open the login activity even the data is successfully inserted.
Here is my ApiClient.java:
public class ApiClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String url){
if(retrofit == null){
retrofit = new Retrofit.Builder().baseUrl(url)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.client(new OkHttpClient().newBuilder()
.connectTimeout(3, TimeUnit.SECONDS)
.readTimeout(3, TimeUnit.SECONDS)
.writeTimeout(3, TimeUnit.SECONDS)
.build())
.build();
}
return retrofit;
}
}
Is there something that I missed? Cause when I try it just the basic ones, I mean like passing it through intent and no post action, it works. But when I try it along with POST action, the error thing comes out
Okay, I've figured out the solution. So basically in the server-side hasn't been registered to SMTP so it makes the connection request via client android become so slow. Therefore, I decided to try it first via the local server and it makes the client working perfectly fine. Nothing's wrong with the client code. Thank You for those who have read my issue. :D
Related
I have a response from retrofit request to "/address/{id}/data" link on my server, where id - query param. When I'm getting response from retrofit, I have link with already pasted param "/address/001/data". How can I get original link without query in Retrofit (/address/{id}/data)?
What you can do
You may have some other options, but you can start with this
Option 1
You can directly access the url from the response returned by retrofit using
response.raw().request().url()
This returns the http url of the request, eg. prints out
okhttp/example-request D: //http://example.com/address/001/data
Option 2
Another is by adding network requests interceptor with the help of okhttp-logging-inceptor.
val logging = HttpLoggingInterceptor()
logging.level = Level.BASIC
val client = OkHttpClient.Builder()
.addInterceptor(logging)
.build()
The option 2 is way better than option 1 since it will be intercepting all the network request in your application without re-doing so much work on each request callback. Also, optionally you can customize the logging level of it and add it only on a specified condition.
Eg. Default log on DEBUG mode
val logging = HttpLoggingInterceptor(HttpLoggingInterceptor.Logger.DEFAULT)
val client = OkHttpClient.Builder()
if (BuildConfig.DEBUG) {
logging.level = HttpLoggingInterceptor.Level.BODY // setting the level
client.addInterceptor(okHttpLoggingInterceptor) // adding interceptor
}
References
https://github.com/square/okhttp/tree/master/okhttp-logging-interceptor
I have seen other threads for this issue but unable to get any proper answer.
#POST("task/GetAllTasks")
Call<MyTask> getMyTasks(#Header("Authorization") String token, #Query("EmployeeId") String emp);
This is how I am calling, at first I thought it is due to GET request data limitation because GET imposes data limits and then I changed request from GET to POST but issue still persists.
ApiUtils.getTaskService().getMyTasks(apiToken, employeeId).enqueue(new Callback<MyTask>() {
#Override
public void onResponse(Call<MyTask> call, Response<MyTask> response) {
// ... Successful code goes here
}
#Override
public void onFailure(Call<MyTask> call, Throwable t) {
//.. This block of code executing now :(
}
}
Always onFailure is being called. I have tested this same request on Postman and it is returning data. Content-Length is content-length →45720
It does work on small amount of data as I have tested it on Dev database which has smaller amount of data but on Live environment it is continuously causing problem.
Please suggest a solution or should I leave Retrofit and move to native Android library for this?
EDIT: Can we increase request timeout in Retrofit, if yes then how?
Try to increase your timeout:
OkHttpClient client = new OkHttpClient().newBuilder()
.readTimeout(10, TimeUnit.SECONDS)
.connectTimeout(10, TimeUnit.SECONDS).build();
And set it to your retrofit:
new Retrofit.Builder().baseUrl("xxx").client(client).build().create(xxx.class);
Use #Part to send big string data it can easily send your data to server side
For ex.
You need to send some string that name is "abc" then in the retrofit code
#Part("abc") //your string variable
Its works for me and I save that data to mediumtext in mysql
and the code is $_REQUEST['abc'];
I'm writing an SDK for our MBaaS service. I use Retrofit2 for my REST calls.
I've an Interceptor (very similar to this) for refreshing an expired token that does a pretty complicated if-else cases. For testing the interceptor, I need to mock our API which I do using MockRetrofit library. So far so good! (See end of question for some info on my interceptor class)
Here's the code:
#Before
public void setup() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BacktoryClient.BASE_URL)
.client(new OkHttpClient.Builder().addInterceptor(new RetryWithRefreshedTokenInterceptor()).build())
.build();
NetworkBehavior behavior = NetworkBehavior.create();
MockRetrofit mockRetrofit = new MockRetrofit.Builder(retrofit)
.networkBehavior(behavior)
.build();
delegate = mockRetrofit.create(AuthApiDefinition.class);
}
#Test
public void testRetryWithRefreshedToken() throws Exception {
SimpleMock apiMock = new SimpleMock(delegate);
Response<SomeApiResponse> response = apiMock.someApiCall(<parameters>).execute();
// assert part
}
The problem is that response object in test method is what it should be (indication that mocking part is OK) but RetryWithRefreshedTokenInterceptor interceptor is not being called. So I assume that MockRetrofit ignores the OkHttpClient.
Now asking the real question, is this some kind of bug or I've completely misunderstood the usage of MockRetrofit library? If it was you, how you were testing the interceptor?
More info on RetryWithRefreshedTokenInterceptor: It checks if the response code is 401 or not and if so calls a method of our SDK which itself calls a method of our API (here from the mocked API) to get a new token and saves that in persistent storage (The amount of logic handled in API methods used in interceptor is big enough I can't isolate the interceptor to test it with MockWebserver)
i'm using Parse server and all is working fine except when i enable localdatastore, most
1 saveInBackroud stop working and also
2 SignUpInBackgroud is singin up a new user but, is not calling back, and it's being impossible to stop a progressDialog
3 Also not saving usersession on signup
Parse.Configuration config = new Parse.Configuration.Builder(this)
.addNetworkInterceptor(new ParseLogInterceptor()) .addNetworkInterceptor(new ParseStethoInterceptor())
.applicationId(PARSE_APP_ID_DEV) .clientKey(PARSE_CLIENT_DEV)
.server(PARSE_SERVER_URL) .enableLocalDataStore() .build();
Parse.initialize(config);
Any help ?
I am using retrofit to deserialize json request from web server and I need to create a session (cookie?) in my app (which should expire in 120 min). The problem is I don't know how to implement it.
private RestAdapter adapter = RestAdapter.Builder().setClient(????).setServer("http://192.168.0.1").build();
This session should persist only if the application is running.
Min SDK requirement is 8
Ok,you know the retrofit actually uses the okhttp inside the framework.
And you should know the "Interceptor"
When you init a okhttp in retrofit, you should invoke addInterceptor, just like this:
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.retryOnConnectionFailure(true);
builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
builder.writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
builder.readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
builder.addInterceptor(new ZCommonIntercepter());
Custom your own Intercepter extends Intercepter.
And get the sessionId by response.header("Set-cookie") save it as a Constant or something in your memory.
Every request after this you should remove the original header("cookie")
and addHeader (the thing that you have already saved)
I'm sorry that i'm not a native english speaker. If you can not understand me. I will just give you some keywords, you can google it.
---Key words---
interceptor in okhttp
cookies in request header or response header