How to set header to all of requests? - android

In my application I used Retrofit for get requests from server.
I want set header to all of requests, I write below codes :
public class ApiClient {
private static final String BASE_URL = "http://example.com/api/v1.0.0.1/Api/";
private static Retrofit retrofit = null;
public static Gson gson = new GsonBuilder().create();
public static Retrofit getClient() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.interceptors().add(interceptor);
builder.addInterceptor(new Interceptor() {
#Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request request = chain.request().newBuilder().addHeader("Device", "2").build();
return chain.proceed(request);
}
});
OkHttpClient client = builder
.connectTimeout(120, TimeUnit.SECONDS)
.writeTimeout(120, TimeUnit.SECONDS)
.readTimeout(120, TimeUnit.SECONDS)
.build();
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.client(client)
.build();
}
return retrofit;
}
}
But when run application, not set this header!
How can I it? please help me

Related

Initializing retrofit class in another class

I am working on a retrofit application and I am following a tutorial, but in the tutorial he always creates the following in every class:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://jsonplaceholder.typicode.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
Now I have created a retro fit class called APIClient, which has the above in it, plus some security. Here is my API client:
public class APIClient {
private static OkHttpClient.Builder httpClient;
private static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl("http://10.0.2.2:8080")
.addConverterFactory(GsonConverterFactory.create());
public static <S> S createService(Class<S> serviceClass) {
return createService(serviceClass, null);
}
public static <S> S createService(Class<S> serviceClass, final Token token) {
if(httpClient == null){
System.out.println("client null");
httpClient = new OkHttpClient.Builder();
if (!token.getToken().contains("null")) {
System.out.println("Token not null " + token.getToken());
httpClient.addInterceptor(new Interceptor() {
#Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request.Builder requestBuilder = original.newBuilder()
.header("Accept", "application/json")
.header("Authorization", token.getToken())
.method(original.method(), original.body());
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
}
httpClient.connectTimeout(50, TimeUnit.SECONDS);
httpClient.addInterceptor(addLogging());
}
OkHttpClient client = httpClient.build();
Retrofit retrofit = builder.client(client).build();
return retrofit.create(serviceClass);
}
private static HttpLoggingInterceptor addLogging(){
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
return logging;
}
}
now in the tutorial I am following he does the following:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://jsonplaceholder.typicode.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
JsonPlaceHolderApi jsonPlaceHolderApi = retrofit.create(JsonPlaceHolderApi.class);
Call<List<Post>> call = jsonPlaceHolderApi.getPosts();
Is there any way I can eliminate the whole Retrofit retrofit = new Retrofit.Builder() with my class but still use the retrofit.create part?
public class APIClient {
private static final String BASE_URL = "http://10.0.2.2:8080/";
private static OkHttpClient.Builder httpClient;
private Retrofit retrofit;
private APIClient() {
Gson gson = new GsonBuilder()
.setLenient()
.create();
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
public static <S> S createService(Class<S> serviceClass) {
return createService(serviceClass, null);
}
public static <S> S createService(Class<S> serviceClass, final MediaSession.Token token) {
if (httpClient == null) {
System.out.println("client null");
httpClient = new OkHttpClient.Builder();
if (!token.getToken().contains("null")) {
System.out.println("Token not null " + token.getToken());
httpClient.addInterceptor(new Interceptor() {
#Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request.Builder requestBuilder = original.newBuilder()
.header("Accept", "application/json")
.header("Authorization", token.getToken())
.method(original.method(), original.body());
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
}
httpClient.connectTimeout(50, TimeUnit.SECONDS);
httpClient.addInterceptor(addLogging());
}
OkHttpClient client = httpClient.build();
Retrofit retrofit = builder.client(client).build();
return retrofit.create(serviceClass);
}
private static HttpLoggingInterceptor addLogging() {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
return logging;
}
}
Call<List<Post>> call = APIClient.createService(JsonPlaceHolderApi.class).getPosts();

How to solve failed connection to service?

I want to get to the service in specific URL .... I use retrofit to get it but it give me an error connection to the URL...while the URL is active in chrome.
in the code I write ??? instead to correct one ^__^ (this code is class APIClient)
and to be sure that I work in correct way I was built an api in mocky site with the same json file .... and it is work
so can any one help me please
public static final String BASE_URL = "http://111.222.1.12:0000/???/???/????/";
//database
public static final String BASE_URL2 = "http://www.mocky.io/v2/";
public static Boolean URL=true;
private static Retrofit retrofit = null;
public static Retrofit getClient(){
if (retrofit==null) {
if(URL)
{
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
else
{
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL2)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
}
return retrofit;
}
Hello you can try using my ApiClient, I'm using rxJava so you need to redesign the APIClient to your need
public class ApiClient {
private static Retrofit retrofit = null;
private static int REQUEST_TIMEOUT = 120;
private static OkHttpClient okHttpClient;
public static Retrofit getClient(Context context) {
if (okHttpClient == null)
initOkHttp(context);
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(API_PATH)
.client(okHttpClient)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
private static void initOkHttp(Context context) {
ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.tlsVersions(TlsVersion.TLS_1_2)
.cipherSuites(
CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256)
.build();
OkHttpClient.Builder httpClient = new OkHttpClient().newBuilder()
.connectTimeout(REQUEST_TIMEOUT, TimeUnit.SECONDS)
.readTimeout(REQUEST_TIMEOUT, TimeUnit.SECONDS)
.writeTimeout(REQUEST_TIMEOUT, TimeUnit.SECONDS);
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient.addInterceptor(interceptor);
httpClient.addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request.Builder requestBuilder = original.newBuilder()
.addHeader("Accept", "application/json")
.addHeader("Request-Type", "Android")
.addHeader("Content-Type", "application/json");
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
okHttpClient = httpClient.build();
}
public static void resetApiClient() {
retrofit = null;
okHttpClient = null;
}
}
Hope this reference can help you solve your problems

How to add http interceptor in retrofit in a service generator class

I created a separate service generator class as shown is this guide https://futurestud.io/tutorials/retrofit-2-manage-request-headers-in-okhttp-interceptor
ApiServiceGenerator.java
public class ApiServiceGenerator {
private static final String BASE_URL = "http://192.168.0.205/hadia/api/";
private static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create());
private static Retrofit retrofit = builder.build();
private static OkHttpClient.Builder httpClient =
new OkHttpClient.Builder();
public static <S> S createService(
Class<S> serviceClass) {
return retrofit.create(serviceClass);
}
}
i need to add an Authorization Header to each request,
how do i do that using this static createService method?
Here is how to create an Interceptor for adding header to each request
httpClient.addInterceptor(new Interceptor() {
#Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
// Request customization: add request headers
Request.Builder requestBuilder = original.newBuilder()
.header("Authorization", "auth-value"); // <-- this is the important line
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
How i add this method to add a Bearer token to each request?
I have a Creator class like this
class Creator {
public static Services newServices() {
final HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
final OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.build();
final Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Services.HOST)
.client(client)
.addConverterFactory(GsonConverterFactory.create(GsonUtils.get()))
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
return retrofit.create(Services.class);
}
}
You need to use the http client created when building the retrofit instance.
Retrofit.Builder()
.baseUrl(BASE_URL)
.client(httpClient) // This is the line
.addConverterFactory(GsonConverterFactory.create());

How to increase upload time for retrofit library in android

I am using retrofit library to upload file to server. When file was uploaded it shows error:: timeout. How to increase upload time so that I can upload full file in server.
Here try this: In below code you will pass your custom OKHTTP client with your custom timeout
public class RetrofitClient {
private static final OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.build();
public static Retrofit retrofit = null;
public static Retrofit getClient(String baseUrl) {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.client(okHttpClient)
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
You also need this dependency:
implementation 'com.squareup.okhttp3:okhttp:3.10.0'// OKHTTP \\ Add this to your gradle file
Add the following class in your project.
public class Api{
static Gson gson = new GsonBuilder()
.setLenient()
.create();
public static Retrofit adapter = new Retrofit.Builder()
.baseUrl(BuildConfig.BASE_URL) //Set the Root URL
.addConverterFactory(GsonConverterFactory.create(gson))
.client(configureTimeouts())
.build(); //Finally building the adapter
public static OkHttpClient configureTimeouts() {
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(90, TimeUnit.SECONDS) // Set your timeout duration here.
.writeTimeout(90, TimeUnit.SECONDS)
.readTimeout(90, TimeUnit.SECONDS)
.build();
return okHttpClient;
}
}
In the above configureTimeouts() function, you can set the duration after which the timeout occurs according to your requirements.
Also, don't forget to put these dependencies in your app level build.gradle file
compile 'com.squareup.retrofit2:retrofit:2.4.0'
compile 'com.squareup.retrofit2:converter-gson:2.4.0'
public RestAdapter providesRestAdapter(Gson gson) {
final OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setReadTimeout(60, TimeUnit.SECONDS);
okHttpClient.setConnectTimeout(60, TimeUnit.SECONDS);
return new RestAdapter.Builder()
.setEndpoint(BuildConfig.BASE_URL)
.setConverter(new GsonConverter(gson))
.setClient(new OkClient(okHttpClient))
.build();
}
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder().readTimeout(120, TimeUnit.SECONDS).connectTimeout(120, TimeUnit.SECONDS)
.writeTimeout(120, TimeUnit.SECONDS);
private static Retrofit retrofit;
static {
Builder addConverterFactory = new Builder().baseUrl(API_BASE_URL).addConverterFactory(GsonConverterFactory.create());
builder = addConverterFactory;
retrofit = addConverterFactory.build();
}
public static <S> S createService(Class<S> serviceClass) {
return createService(serviceClass, null, null);
}
public static <S> S createService(Class<S> serviceClass, String username, String password) {
if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
return createService(serviceClass, null);
}
return createService(serviceClass, Credentials.basic(username, password));
}
public static <S> S createService(Class<S> serviceClass, String authToken) {
if (!TextUtils.isEmpty(authToken)) {
AuthenticationInterceptor interceptor = new AuthenticationInterceptor(authToken);
if (!httpClient.interceptors().contains(interceptor)) {
httpClient.addInterceptor(interceptor);
builder.client(httpClient.build());
retrofit = builder.build();
}
}
return retrofit.create(serviceClass);
}

Code implementation Singleton Design Pattern: Bill Pugh on a Retrofit object

I have been trying to implement the Bill Pugh Singleton Design Pattern using a private static class to return the singleton retrofit instance. SO far I have been able to come up with the following code. Can someone help me review this code and confirm if this is a proper implementation of the singleton design pattern suggested by Mr. Bill Pugh Himself or suggest me a proper way of implementing this.
public class SingletonRetrofit {
private SingletonRetrofit(){}
private static class SingletonRetrofitHelper {
private static OkHttpClient okHttpClient;
private static Retrofit retrofit;
private static Retrofit makeRetrofit() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
okHttpClient = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.readTimeout(20, TimeUnit.SECONDS)
.connectTimeout(15, TimeUnit.SECONDS)
.build();
retrofit = new Retrofit.Builder()
.baseUrl("http://ci.draftserver.com/hornsbyapp/webservice/")
.client(okHttpClient)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit;
}
}
public static Retrofit getInstance() {
return SingletonRetrofitHelper.makeRetrofit();
}
}
USE this one:
public class Apiclient {
private static final String BASE_URL ="URL";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit == null) {
OkHttpClient.Builder httpClient2 = new OkHttpClient.Builder();
httpClient2.addNetworkInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request.Builder builder = chain.request().newBuilder();
builder.addHeader("site_id","1");
return chain.proceed(builder.build());
}
});
OkHttpClient client = httpClient2.build();
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}

Categories

Resources