retrofit2.converter.gson.GsonConverterFactory Java Examples

The following examples show how to use retrofit2.converter.gson.GsonConverterFactory. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ApiService.java    From tenor-android-core with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized T create(@NonNull Builder<T> builder) {
    Context ctx = builder.context;
    if (!(ctx instanceof Application)) {
        ctx = ctx.getApplicationContext();
    }

    final File cacheDir = new File(ctx.getCacheDir().getAbsolutePath(), ctx.getPackageName());
    final Cache cache = new Cache(cacheDir, 10 * 1024 * 1024);

    OkHttpClient.Builder http = new OkHttpClient.Builder()
            .cache(cache)
            .writeTimeout(builder.timeout, TimeUnit.SECONDS);

    for (Interceptor interceptor : builder.interceptors) {
        http.addInterceptor(interceptor);
    }

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(builder.endpoint)
            .client(http.build())
            .addConverterFactory(GsonConverterFactory.create(builder.gson))
            .build();

    return retrofit.create(builder.cls);
}
 
Example #2
Source File: DownloadManager.java    From RetrofitClient with MIT License 6 votes vote down vote up
public void addDownloadInfo(DownloadInfo info) {
    info.setState(DownloadInfo.DOWNLOAD);
    if (info == null || subscriberMap.get(info.getUrl()) != null) {
        subscriberMap.get(info.getUrl()).setDownloadInfo(info);
        return;
    }
    DownloadSubscriber subscriber = new DownloadSubscriber(info);
    subscriberMap.put(info.getUrl(), subscriber);
    CommonRequest commonRequest;
    if (!downloadInfos.contains(info)) {
        DownloadInterceptor interceptor = DownloadInterceptor.create(info, subscriber);
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(60, TimeUnit.SECONDS);
        builder.addInterceptor(interceptor);
        Retrofit.Builder retrofitBuilder = new Retrofit.Builder()
                .client(builder.build())
                .baseUrl(HttpManager.getBaseUrl())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create());
        commonRequest = retrofitBuilder.build().create(CommonRequest.class);
        info.setRequest(commonRequest);
        downloadInfos.add(info);
    }
}
 
Example #3
Source File: NightscoutFollow.java    From xDrip with GNU General Public License v3.0 6 votes vote down vote up
public static Retrofit getRetrofitInstance() throws IllegalArgumentException {
    if (retrofit == null) {
        final String url = getUrl();
        if (emptyString(url)) {
            UserError.Log.d(TAG, "Empty url - cannot create instance");
            return null;
        }
        final HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        if (D) {
            httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        }
        final OkHttpClient client = enableTls12OnPreLollipop(new OkHttpClient.Builder())
                .addInterceptor(httpLoggingInterceptor)
                .addInterceptor(new InfoInterceptor(TAG))
                .addInterceptor(new GzipRequestInterceptor())
                .build();

        retrofit = new retrofit2.Retrofit.Builder()
                .baseUrl(url)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    return retrofit;
}
 
Example #4
Source File: ApiClient.java    From Learning-Resources with MIT License 6 votes vote down vote up
private void initAPIClient() {

        OkHttpClient.Builder okBuilder = MyOkHttpBuilder.getOkHttpBuilder(context);

//		okBuilder.retryOnConnectionFailure(true);
//      okBuilder.followRedirects(false);

        OkHttpClient httpClient = okBuilder.connectTimeout(HTTP_TIMEOUT, timeUnit)
                .writeTimeout(HTTP_TIMEOUT, timeUnit)
                .readTimeout(HTTP_TIMEOUT, timeUnit)
                .build();

        Retrofit.Builder builder = new Retrofit.Builder();

        retrofit = builder
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(API_BASE_URL)
                .client(httpClient)
                .build();

        mApiService = retrofit.create(ApiService.class);
    }
 
Example #5
Source File: NetTestDataManager.java    From QuickDevFramework with Apache License 2.0 6 votes vote down vote up
public NetTestDataManager() {
        // 这些配置可以放在App工程的网络模块中,这里简要处理就不写了
        HttpInfoCatchInterceptor infoCatchInterceptor = new HttpInfoCatchInterceptor();
        infoCatchInterceptor.setCatchEnabled(true);
        infoCatchInterceptor.setHttpInfoCatchListener(new HttpInfoCatchListener() {
            @Override
            public void onInfoCaught(HttpInfoEntity entity) {
                entity.logOut();
                //do something......
            }
        });
    
        OkHttpClient.Builder okBuilder = new OkHttpClient.Builder();
//        okBuilder.cookieJar(RetrofitManager.());
        okBuilder.addInterceptor(infoCatchInterceptor);
        RetrofitManager.configTrustAll(okBuilder);
    
        Retrofit.Builder builder = new Retrofit.Builder();
        builder.baseUrl("http://www.weather.com.cn/")
        .client(okBuilder.build())
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .addConverterFactory(GsonConverterFactory.create());
        
        clientApi = builder.build().create(ClientApi.class);
    }
 
Example #6
Source File: ApiClient.java    From GracefulMovies with Apache License 2.0 6 votes vote down vote up
public ApiClient() {
    mRetrofitBuilder = new Retrofit.Builder()
            .baseUrl("https://api-m.mtime.cn/")
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create());

    mOkHttpClientBuilder = new OkHttpClient.Builder();
    mOkHttpClientBuilder.connectTimeout(15, TimeUnit.SECONDS);
    if (BuildConfig.DEBUG) {
        mOkHttpClientBuilder.addNetworkInterceptor(
                new LoggingInterceptor.Builder()
                        .loggable(BuildConfig.DEBUG)
                        .setLevel(Level.BODY)
                        .log(Platform.INFO)
                        .request("Request")
                        .response("Response")
                        .build()
        );
    }
}
 
Example #7
Source File: RetrofitHelper.java    From CleanArch with MIT License 6 votes vote down vote up
public static SampleService getSampleService() {

        if (service == null) {

            synchronized (RetrofitHelper.class) {

                if (service == null) {
                    Retrofit retrofit = new Retrofit.Builder()
                            .baseUrl("http://gank.io/")
                            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                            .addConverterFactory(GsonConverterFactory.create())
                            .build();
                    service = retrofit.create(SampleService.class);
                }
            }
        }

        return service;
    }
 
Example #8
Source File: SlackConfig.java    From oneops with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize slack web api client.
 *
 * @return {@link SlackWebClient}
 */
@Bean
public SlackWebClient getWebClient() {
    OkHttpClient client = new OkHttpClient.Builder()
            .readTimeout(slackTimeout, SECONDS)
            .connectTimeout(slackTimeout, SECONDS)
            .retryOnConnectionFailure(true)
            .build();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(slackUrl)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create(SlackWebClient.gson))
            .build();
    return retrofit.create(SlackWebClient.class);
}
 
Example #9
Source File: ForecastClient.java    From forecast-android with Apache License 2.0 6 votes vote down vote up
private ForecastClient(ForecastConfiguration forecastConfiguration) {
    Retrofit retrofit = new Retrofit.Builder().baseUrl(Constants.API_BASE_URL)
            .addConverterFactory(GsonConverterFactory.create(createGson()))
            .client(createOkHttpClient(forecastConfiguration))
            .build();
    mApiKey = forecastConfiguration.getApiKey();
    mLanguage = forecastConfiguration.getDefaultLanguage();
    mUnit = forecastConfiguration.getDefaultUnit();
    if (forecastConfiguration.getDefaultExcludeList() != null) {
        mExcludeBlocks = new ArrayList<>(forecastConfiguration.getDefaultExcludeList());
    }
    CacheControl cacheControl =
            new CacheControl.Builder().maxAge(forecastConfiguration.getCacheMaxAge(), TimeUnit.SECONDS)
                    .build();
    mCacheControl = cacheControl.toString();
    mService = retrofit.create(ForecastService.class);
}
 
Example #10
Source File: FetchReviewsTask.java    From popular-movies-app with Apache License 2.0 6 votes vote down vote up
@Override
protected List<Review> doInBackground(Long... params) {
    // If there's no movie id, there's nothing to look up.
    if (params.length == 0) {
        return null;
    }
    long movieId = params[0];

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://api.themoviedb.org/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    MovieDatabaseService service = retrofit.create(MovieDatabaseService.class);
    Call<Reviews> call = service.findReviewsById(movieId,
            BuildConfig.THE_MOVIE_DATABASE_API_KEY);
    try {
        Response<Reviews> response = call.execute();
        Reviews reviews = response.body();
        return reviews.getReviews();
    } catch (IOException e) {
        Log.e(LOG_TAG, "A problem occurred talking to the movie db ", e);
    }

    return null;
}
 
Example #11
Source File: ClientModule.java    From Aurora with Apache License 2.0 6 votes vote down vote up
/**
 * 提供 {@link Retrofit}
 *
 * @param builder
 * @param client
 * @param httpUrl
 * @return
 * @author: jess
 * @date 8/30/16 1:15 PM
 */
@Singleton
@Provides
Retrofit provideRetrofit(Application application, @Nullable RetrofitConfiguration configuration, Retrofit.Builder builder, OkHttpClient client
        , HttpUrl httpUrl, Gson gson) {
    builder
            .baseUrl(httpUrl)//域名
            .client(client);//设置okhttp

    if (configuration != null)
        configuration.configRetrofit(application, builder);

    builder
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//使用 Rxjava
            .addConverterFactory(GsonConverterFactory.create(gson));//使用 Gson
    return builder.build();
}
 
Example #12
Source File: DroidKaigiClient.java    From droidkaigi2016 with Apache License 2.0 6 votes vote down vote up
@Inject
public DroidKaigiClient(OkHttpClient client) {
    Retrofit feedburnerRetrofit = new Retrofit.Builder()
            .client(client)
            .baseUrl("https://raw.githubusercontent.com")
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create(createGson()))
            .build();
    service = feedburnerRetrofit.create(DroidKaigiService.class);

    Retrofit googleFormRetrofit = new Retrofit.Builder()
            .client(client)
            .baseUrl("https://docs.google.com/forms/d/")
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create(createGson()))
            .build();
    googleFormService = googleFormRetrofit.create(GoogleFormService.class);

    Retrofit githubRetrofit = new Retrofit.Builder()
            .client(client)
            .baseUrl("https://api.github.com")
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create(createGson()))
            .build();
    githubService = githubRetrofit.create(GithubService.class);
}
 
Example #13
Source File: MainActivity.java    From RxEasyHttp with Apache License 2.0 6 votes vote down vote up
public void onCustomApiCall(View view) {
    final String name = "18688994275";
    final String pass = "123456";
    final CustomRequest request = EasyHttp.custom()
            .addConverterFactory(GsonConverterFactory.create(new Gson()))
            .sign(true)
            .timeStamp(true)
            .params(ComParamContact.Login.ACCOUNT, name)
            .params(ComParamContact.Login.PASSWORD, MD5.encrypt4login(pass, AppConstant.APP_SECRET))
            .build();

    LoginService mLoginService = request.create(LoginService.class);
    Observable<AuthModel> observable = request.apiCall(mLoginService.login("v1/account/login", request.getParams().urlParamsMap));
    Disposable disposable = observable.subscribe(new Consumer<AuthModel>() {
        @Override
        public void accept(@NonNull AuthModel authModel) throws Exception {
            showToast(authModel.toString());
        }
    }, new Consumer<Throwable>() {
        @Override
        public void accept(@NonNull Throwable throwable) throws Exception {
            showToast(throwable.getMessage());
        }
    });
    //EasyHttp.cancelSubscription(disposable);//取消订阅
}
 
Example #14
Source File: MovieDbAdapterProvider.java    From Android-App-Architecture-MVVM-Databinding with Apache License 2.0 6 votes vote down vote up
/**
 * Create a new instance for {@link IMovieDbApi IMovieDbApi} interface.
 * The requests will run in OkHttp's internal thread pool.
 */
@NonNull
/* default */ static IMovieDbApi create(@NonNull final OkHttpClient httpClient) {
    // Set GSON naming policy
    final Gson gson = new GsonBuilder()
            .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .create();

    final Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(API_ENDPOINT)
            .addCallAdapterFactory(RxJava2CallAdapterFactory.createAsync()) // Use OkHttp's internal thread pool.
            .addConverterFactory(GsonConverterFactory.create(gson))
            .client(httpClient)
            .build();

    return retrofit.create(IMovieDbApi.class);
}
 
Example #15
Source File: BookRetrofit.java    From fingerpoetry-android with Apache License 2.0 5 votes vote down vote up
public BookRetrofit() {
    context = BookBoxApplication.getInstance().getApplicationContext();

    OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();

    httpClientBuilder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
    //设置缓存目录
    try {
        if (context.getCacheDir() != null) {
            File cacheDirectory = new File(context.getCacheDir()
                    .getAbsolutePath(), "HttpCache");
            Cache cache = new Cache(cacheDirectory, 20 * 1024 * 1024);
            httpClientBuilder.cache(cache);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    okHttpClient = httpClientBuilder.build();
    Retrofit retrofit = new Retrofit.Builder()
            .client(okHttpClient)
            .baseUrl(BASE_API_URL)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .build();

    accountApi = retrofit.create(AccountApi.class);
    siteApi = retrofit.create(SiteApi.class);
    topicApi = retrofit.create(TopicApi.class);
    articleApi = retrofit.create(ArticleApi.class);
    sysApi = retrofit.create(SysApi.class);
    novelApi = retrofit.create(NovelApi.class);
    wxArticleApi = retrofit.create(WxArticleApi.class);
    jokeApi = retrofit.create(JokeApi.class);
}
 
Example #16
Source File: AboutActivityModule.java    From Ency with Apache License 2.0 5 votes vote down vote up
@UpdateURL
@Provides
@ActivityScope
Retrofit provideUpdateRetrofit(Retrofit.Builder builder, OkHttpClient client) {
    return builder
            .baseUrl(UpdateApi.HOST)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build();
}
 
Example #17
Source File: DemoModule.java    From pandroid with Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
ReviewService provideDemoService(OkHttpClient.Builder clientBuilder, Context context, LogWrapper logWrapper) {
    //PandroidCall handle Action Delegate on main thread and mock annotation
    PandroidCallAdapterFactory factory = PandroidCallAdapterFactory.create(context, logWrapper);
    factory.setMockEnable(PandroidConfig.DEBUG);
    Retrofit.Builder builder = new Retrofit.Builder()
            .client(clientBuilder.build())
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(factory)
            .baseUrl(BuildConfig.BASE_URL_PRODUCT);
    return builder.build().create(ReviewService.class);
}
 
Example #18
Source File: UpWalletTickerService.java    From Upchain-wallet with GNU Affero General Public License v3.0 5 votes vote down vote up
private void buildApiClient(String baseUrl) {
    apiClient = new Retrofit.Builder()
            .baseUrl(baseUrl + "/")
            .client(httpClient)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build()
            .create(ApiClient.class);
}
 
Example #19
Source File: BlockExplorerClient.java    From Upchain-wallet with GNU Affero General Public License v3.0 5 votes vote down vote up
private void buildApiClient(String baseUrl) {
	transactionsApiClient = new Retrofit.Builder()
			.baseUrl(baseUrl)
			.client(httpClient)
			.addConverterFactory(GsonConverterFactory.create(gson))
			.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
			.build()
			.create(TransactionsApiClient.class);
}
 
Example #20
Source File: Twitch.java    From Discord-Streambot with MIT License 5 votes vote down vote up
public Twitch(String clientID, String accessToken) {
    OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new HeaderInterceptor(accessToken, clientID)).build();
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://api.twitch.tv/kraken/")
            .addConverterFactory(GsonConverterFactory.create())
            .client(client)
            .build();
    this.service = retrofit.create(TwitchService.class);
}
 
Example #21
Source File: RetrofitManager.java    From BaseQuickAdapter with Apache License 2.0 5 votes vote down vote up
public static RetrofitService getService() {
    if (sRetrofit == null) {
        synchronized (RetrofitManager.class) {
            if (sRetrofit == null) {
                sRetrofit = new Retrofit.Builder()
                        .baseUrl(BASE_URL)
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();
            }
        }
    }
    return sRetrofit.create(RetrofitService.class);
}
 
Example #22
Source File: ApiClient.java    From Android-Example with Apache License 2.0 5 votes vote down vote up
public static Retrofit getInstance(){
  if(retrofit == null){
    retrofit = new Retrofit.Builder().baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .build();
  }
  return retrofit;
}
 
Example #23
Source File: ApiClient.java    From Android-MVP-with-Retrofit with MIT License 5 votes vote down vote up
/**
 * This method returns retrofit client instance
 *
 * @return Retrofit object
 */
public static Retrofit getClient() {
    if (retrofit == null) {
        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    return retrofit;
}
 
Example #24
Source File: ApplicationModule.java    From scallop with MIT License 5 votes vote down vote up
@Provides
@Singleton
Retrofit provideRetrofit() {
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Constants.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build();
    return retrofit;
}
 
Example #25
Source File: ApiFactory.java    From AndroidSchool with Apache License 2.0 5 votes vote down vote up
@NonNull
private static Retrofit buildRetrofit() {
    return new Retrofit.Builder()
            .baseUrl(BuildConfig.API_ENDPOINT)
            .client(getClient())
            .addConverterFactory(GsonConverterFactory.create())
            .build();
}
 
Example #26
Source File: APIService.java    From DrySister with GNU Lesser General Public License v3.0 5 votes vote down vote up
private APIService() {
    Retrofit storeRestAPI = new Retrofit.Builder().baseUrl(BASE_URL)
            .client(DryInit.mOkHttpClient)
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    apis = storeRestAPI.create(APIs.class);
}
 
Example #27
Source File: MercuryWalletTickerService.java    From ETHWallet with GNU General Public License v3.0 5 votes vote down vote up
private void buildApiClient(String baseUrl) {
    apiClient = new Retrofit.Builder()
            .baseUrl(baseUrl)
            .client(httpClient)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build()
            .create(ApiClient.class);
}
 
Example #28
Source File: NetModule.java    From WanAndroid with GNU General Public License v3.0 5 votes vote down vote up
@Singleton
@Provides
static API provideAPI(OkHttpClient client) {
    return new Retrofit.Builder()
            .baseUrl(BuildConfig.BASE_URL)
            .addConverterFactory(ScalarsConverterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .client(client)
            .build()
            .create(API.class);
}
 
Example #29
Source File: RetrofitClient.java    From orz with Apache License 2.0 5 votes vote down vote up
public static Retrofit getJokeRetrofit() {

        Gson gson = MyGson.get();
        OkHttpClient client = MyOkClient.getOkHttpClient();

        return new Retrofit.Builder().baseUrl(BuildConfig.BASE_URL_JOKE)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(client)
                .build();
    }
 
Example #30
Source File: NetworkModule.java    From JReadHub with GNU General Public License v3.0 5 votes vote down vote up
private Retrofit createRetrofit(Retrofit.Builder builder, OkHttpClient okHttpClient, String url) {
    return builder
            .baseUrl(url)
            .client(okHttpClient)
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .build();
}