As I need to initialize add headers as global to get headers in all API call, I have tried but while debug its not sending the headers in API call.
val client = OkHttpClient.Builder()
.authenticator { _, response ->
response.request().newBuilder().addHeader(
"authorization","123").build()
}
.connectTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.build()
AndroidNetworking.initialize(applicationContext, client)
Can you replace your code with mentioned below and try again
OkHttpClient.Builder().add(new Interceptor() {
#Override
public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
Request.Builder requestBuilder = chain.request().newBuilder();
requestBuilder.header("Content-Type", "application/json");
return chain.proceed(requestBuilder.build());
}
})
.connectTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.build()
AndroidNetworking.initialize(applicationContext, client)
Related
I got this error:
Fatal Exception: kotlin.KotlinNullPointerException
com.example.manager.helper.my_api.MyServiceGenerator$createService$$inlined$-addInterceptor$1.intercept (Interceptor.kt:81)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.kt:100)
okhttp3.internal.connection.RealCall.getResponseWithInterceptorChain$okhttp (RealCall.kt:197)
okhttp3.internal.connection.RealCall$AsyncCall.run (RealCall.kt:502)
java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1133)
java.lang.Thread.run (Thread.java:762)
And I have no idea why it caused.
What I implemented is:
val logging = HttpLoggingInterceptor()
if (BuildConfig.DEBUG) { // If Build is Debug Mode, Show Log
logging.level = HttpLoggingInterceptor.Level.BODY // Logs request and response lines and their respective headers and bodies (if present).
} else { // Otherwise, show nothing.
logging.level = HttpLoggingInterceptor.Level.NONE // No logs
}
val client = OkHttpClient.Builder()
client.addInterceptor {
val original = it.request()
val request = original.newBuilder()
.header("User-Agent", MyApp.httpUserAgent!!)
.build()
it.proceed(request)
}
client.addInterceptor(logging)
.connectTimeout(30, TimeUnit.SECONDS)
.callTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
You are not finished building of your client. That's why it's null. In general you forgot to call build() method.
That's how it have to be implemented.
val client = OkHttpClient.Builder()
.addInterceptor(logging)
.connectTimeout(30, TimeUnit.SECONDS)
.callTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.build()
If you're using !! in your codes you should use it with a null check. Like this
if(MyApp.httpUserAgent != null) {
val request = original.newBuilder()
.header("User-Agent", MyApp.httpUserAgent!!)
.build()
else {
//here do something in case of null
}
I have the same problem when upgrade logging-interceptor from 3.10.0 to 4.7.2
Debug find cause is ssl factory
// old code
builder.sslSocketFactory(sslSocketFactory)
change the code to new code
// new code
builder.sslSocketFactory(sslSocketFactory, x509TrustManager)
Sometimes I am getting error “unexpected end of stream on connection” while calling web service from android using go daddy server and hosting.
In pick hours my application got this error.
AppController.class
private void initRetrofitConfig() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(BuildConfig.DEBUG ? HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.NONE);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request().newBuilder().addHeader("Connection", "close").build();
return chain.proceed(request);
}
})
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(1, TimeUnit.MINUTES)
.writeTimeout(5, TimeUnit.MINUTES)
.retryOnConnectionFailure(true)
.build();
Retrofit retrofit = new Retrofit.Builder()
.client(client)
.baseUrl(SERVICE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
.build();
apiEndpoint = retrofit.create(ApiEndpoint.class);
}
public ApiEndpoint getApiEndpoint() {
if (apiEndpoint == null) {
initRetrofitConfig();
}
return apiEndpoint;
}
My app is using Retrofit+okhttp.
Sometimes, it throw SocketTimeoutException just through
1s~3s after request but my okhttp timeout is setting 10s.
It's my code.
private static OkHttpClient getClient() {
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.addInterceptor(headerinterceptor)
.build();
return client;
}
public static XXXX XXXX() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(XXXX)
.addConverterFactory(StatusProcessConverter.create(new GsonBuilder().setLenient().create()))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(getClient())
.build();
XXXX methods = retrofit.create(XXXX.class);
return methods;
}
Can anyone help me ... why the sockettimeout occur less than 10s...
OkHttpClient client;
client = new OkHttpClient.Builder()
.connectTimeout(5, TimeUnit.SECONDS)
.writeTimeout(5, TimeUnit.SECONDS)
.readTimeout(5, TimeUnit.SECONDS)
.build();
Request request22 = new Request.Builder()
.url("http://www.goo.com/")
.build();
Utils.myLog("-begin-");
Response response = null;
try {
response = client.newCall(request22).execute();
if (response.isSuccessful()) {
Utils.myLog("-donw-");
}
} catch (Exception e) {
e.printStackTrace();
Utils.myLog("-error-" + e.toString());
}
This is my code, I have set timeout to 5 seconds, but it still taked 20 seconds to receive "error unknownhostexception " after "begin"? why my code is useless? I have looked the source code of OKHTTP, default timeout is 10 seconds(if I'm right), I'm confused.
Anyone can help, id really appreciated.
For now, OkHttp can't interrupt time-consuming DNS requests (see https://github.com/square/okhttp/issues/95), but you still can do something like this:
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.readTimeout(15, TimeUnit.SECONDS)
.writeTimeout(15, TimeUnit.SECONDS)
.connectTimeout(15, TimeUnit.SECONDS)
.dns(hostname -> Single.fromCallable(
() -> Arrays.asList(InetAddress.getAllByName(hostname))
).timeout(15, TimeUnit.SECONDS)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.computation())
.onErrorReturnItem(new ArrayList<>())
.blockingGet())
.build();
Kotlin
class CustomDns : Dns {
override fun lookup(hostname: String): List<InetAddress> {
return Single.fromCallable {
InetAddress.getAllByName(hostname)
}.timeout(15, TimeUnit.SECONDS)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.computation())
.onErrorReturnItem(arrayOf())
.blockingGet().toList()
}
}
OkHttpClient.Builder()
.connectTimeout(15, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(15, TimeUnit.SECONDS)
.dns(CustomDns())
.build()
I referred this link but I can't seem to implement for mine
I am using
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
I am using the below code, How to set timeout for this !
public class ApiClient {
public static final String BASE_URL = Constants.BaseURL;
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;
}
}
Configure OkHttpClient for timeout option. Then use this as client for Retrofit.Builder.
final OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(20, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build();
Use this okHttpClient for Retrofit#Builder
Retrofit.Builder()
.client(okHttpClient);
Official OkHttp documentation about timeout is here
try below code, it sét timeout is 20 seconds and readTimeout is 30 seconds
private OkHttpClient getRequestHeader() {
OkHttpClient httpClient = new OkHttpClient();
httpClient.setConnectTimeout(20, TimeUnit.SECONDS);
httpClient.setReadTimeout(30, TimeUnit.SECONDS);
return httpClient;
}
Then
public class ApiClient {
public static final String BASE_URL = Constants.BaseURL;
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(getRequestHeader())
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
I have used bellow like in Kotlin with MVVM Model..
var okHttpClient: OkHttpClient? = OkHttpClient.Builder()
.connectTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.build()
private val api = Retrofit.Builder()
.baseUrl(baseurl)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(okHttpClient)
.build()
.create(Api::class.java);
If you are using "com.squareup.retrofit2:retrofit:2.4.0" retrofit version > 2 then you try this one:
private OkHttpClient getRequestHeader()
{
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.readTimeout(60, TimeUnit.SECONDS)
.connectTimeout(60, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.build();
return okHttpClient;
}
In Kotlin you can Configure timeout for Retrofit by
Create OkHttpClient object with time in seconds (The default value is 10 seconds)
private val okHttpClient = OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build()
Then use this object for Retrofit Builder
private val retrofit = Retrofit.Builder()
.addConverterFactory(ScalarsConverterFactory.create())
.client(okHttpClient)
.baseUrl(BASE_URL)
.build()
And import these
import java.util.concurrent.TimeUnit
import okhttp3.OkHttpClient
import retrofit2.Retrofit