Java Code Examples for retrofit2.converter.gson.GsonConverterFactory

The following examples show how to use retrofit2.converter.gson.GsonConverterFactory. These examples are extracted from open source projects. 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 Project: tenor-android-core   Source File: ApiService.java    License: 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 Project: RetrofitClient   Source File: DownloadManager.java    License: 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 Project: xDrip   Source File: NightscoutFollow.java    License: 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 Project: Pixiv-Shaft   Source File: Retro.java    License: MIT License 6 votes vote down vote up
private static Retrofit buildRetrofit(String baseUrl) {
    OkHttpClient.Builder builder = getLogClient();
    try {
        builder.addInterceptor(chain ->
                chain.proceed(addHeader(chain.request().newBuilder()).build()));
        if (!baseUrl.equals(ACCOUNT_BASE_URL)) {
            builder.addInterceptor(new TokenInterceptor());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (Shaft.sSettings.isAutoFuckChina()) {
        builder.sslSocketFactory(new RubySSLSocketFactory(), new pixivOkHttpClient());
        //builder.dns(new CloudFlareDns(CloudFlareDNSService.Companion.invoke()));
        builder.dns(HttpDns.getInstance());
    }
    OkHttpClient client = builder.build();
    Gson gson = new GsonBuilder().setLenient().create();
    return new Retrofit.Builder()
            .client(client)
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create(gson))
            .baseUrl(baseUrl)
            .build();
}
 
Example 5
Source Project: Learning-Resources   Source File: ApiClient.java    License: 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 6
Source Project: QuickDevFramework   Source File: NetTestDataManager.java    License: 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 7
Source Project: GracefulMovies   Source File: ApiClient.java    License: 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 8
Source Project: CleanArch   Source File: RetrofitHelper.java    License: 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 9
Source Project: oneops   Source File: SlackConfig.java    License: 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 10
Source Project: forecast-android   Source File: ForecastClient.java    License: 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 11
Source Project: popular-movies-app   Source File: FetchReviewsTask.java    License: 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 12
Source Project: Aurora   Source File: ClientModule.java    License: 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 13
Source Project: droidkaigi2016   Source File: DroidKaigiClient.java    License: 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 14
Source Project: RxEasyHttp   Source File: MainActivity.java    License: 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 15
/**
 * 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 16
Source Project: fingerpoetry-android   Source File: BookRetrofit.java    License: 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 17
Source Project: Ency   Source File: AboutActivityModule.java    License: 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 18
Source Project: pandroid   Source File: DemoModule.java    License: 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 19
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 20
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 21
Source Project: Discord-Streambot   Source File: Twitch.java    License: 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 22
Source Project: BaseQuickAdapter   Source File: RetrofitManager.java    License: 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 23
Source Project: Android-Example   Source File: ApiClient.java    License: 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 24
Source Project: Android-MVP-with-Retrofit   Source File: ApiClient.java    License: 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 25
Source Project: scallop   Source File: ApplicationModule.java    License: 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 26
Source Project: AndroidSchool   Source File: ApiFactory.java    License: 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 27
Source Project: DrySister   Source File: APIService.java    License: 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 28
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 29
Source Project: WanAndroid   Source File: NetModule.java    License: 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 30
Source Project: orz   Source File: RetrofitClient.java    License: 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();
    }