Java Code Examples for retrofit2.converter.moshi.MoshiConverterFactory

The following are top voted examples for showing how to use retrofit2.converter.moshi.MoshiConverterFactory. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: okuki   File: SwapiModule.java   View source code 7 votes vote down vote up
@Inject
public SwapiModule(OkHttpClient okHttpClient, Moshi moshi) {
    final Retrofit swapiRetrofit = new Retrofit.Builder().baseUrl(Swapi.BASE_URL)
            .client(okHttpClient)
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(MoshiConverterFactory.create(moshi))
            .build();
    bind(Swapi.class).toInstance(swapiRetrofit.create(Swapi.class));
    final Retrofit searchRetrofit = new Retrofit.Builder().baseUrl(CustomSearch.BASE_URL)
            .client(okHttpClient)
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(MoshiConverterFactory.create(moshi))
            .build();
    bind(CustomSearch.class).toInstance(searchRetrofit.create(CustomSearch.class));
    bind(SwapiListDataManager.class).singletonInScope();
}
 
Example 2
Project: toshi-headless-client   File: IdService.java   View source code 6 votes vote down vote up
public IdService(HDWallet wallet, String baseUrl) {
    this.wallet = wallet;

    //final RxJavaCallAdapterFactory rxAdapter = RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io());
    this.client = new OkHttpClient.Builder();

    addUserAgentHeader();
    addSigningInterceptor();
    addLogging();

    final Moshi moshi = new Moshi.Builder().build();

    final Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(baseUrl)
            .addConverterFactory(MoshiConverterFactory.create(moshi))
            //.addCallAdapterFactory(rxAdapter)
            .client(client.build())
            .build();
    this.idInterface = retrofit.create(IdInterface.class);
}
 
Example 3
Project: toshi-headless-client   File: BalanceService.java   View source code 6 votes vote down vote up
public BalanceService(HDWallet wallet, String baseUrl) {
    //final RxJavaCallAdapterFactory rxAdapter = RxJavaCallAdapterFactory
    //        .createWithScheduler(Schedulers.io());
    this.client = new OkHttpClient.Builder();
    this.client.addInterceptor(new UserAgentInterceptor());
    this.client.addInterceptor(new SigningInterceptor(wallet));

    final HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new LoggingInterceptor());
    interceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
    this.client.addInterceptor(interceptor);

    final Moshi moshi = new Moshi.Builder()
                                .add(new BigIntegerAdapter())
                                .build();

    final Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(baseUrl)
            .addConverterFactory(MoshiConverterFactory.create(moshi))
            .client(client.build())
            .build();
    this.balanceInterface = retrofit.create(BalanceInterface.class);
}
 
Example 4
Project: ocreader   File: API.java   View source code 6 votes vote down vote up
API(Context context, Level apiLevel) {
    this.apiLevel = apiLevel;
    final Moshi moshi = new Moshi.Builder()
            .add(Folder.class, new FolderTypeAdapter())
            .add(Feed.class, new FeedTypeAdapter())
            .add(Item.class, new ItemTypeAdapter())
            .add(User.class, new UserTypeAdapter())
            .add(Status.class, new StatusTypeAdapter())
            .build();

    converterFactory = MoshiConverterFactory.create(moshi);

    errorJsonAdapter = moshi.adapter(NewsError.class);

    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    String username = Preferences.USERNAME.getString(sharedPreferences);
    if (username != null) {
        String password = Preferences.PASSWORD.getString(sharedPreferences);
        String url = Preferences.URL.getString(sharedPreferences);
        setupApi(new HttpManager(username, password, HttpUrl.parse(url)));
    }
}
 
Example 5
Project: toshi-android-client   File: EthereumService.java   View source code 6 votes vote down vote up
private EthereumInterface buildEthereumInterface(final String baseUrl) {
    final Moshi moshi = new Moshi.Builder()
            .add(new BigIntegerAdapter())
            .build();

    final RxJavaCallAdapterFactory rxAdapter = RxJavaCallAdapterFactory
            .createWithScheduler(Schedulers.io());

    final Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(baseUrl)
            .addConverterFactory(MoshiConverterFactory.create(moshi))
            .addCallAdapterFactory(rxAdapter)
            .client(this.client.build())
            .build();
    return retrofit.create(EthereumInterface.class);
}
 
Example 6
Project: toshi-android-client   File: IdService.java   View source code 6 votes vote down vote up
private IdService() {
    final RxJavaCallAdapterFactory rxAdapter = RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io());
    final File cachePath = new File(BaseApplication.get().getCacheDir(), "idCache");
    this.cache = new Cache(cachePath, 1024 * 1024 * 2);
    this.client = new OkHttpClient
            .Builder()
            .cache(this.cache)
            .addNetworkInterceptor(new ReadFromCacheInterceptor())
            .addInterceptor(new OfflineCacheInterceptor());

    addUserAgentHeader();
    addSigningInterceptor();
    addLogging();

    final Moshi moshi = new Moshi.Builder()
            .add(new RealmListAdapter())
            .build();

    final Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BaseApplication.get().getResources().getString(R.string.id_url))
            .addConverterFactory(MoshiConverterFactory.create(moshi))
            .addCallAdapterFactory(rxAdapter)
            .client(client.build())
            .build();
    this.idInterface = retrofit.create(IdInterface.class);
}
 
Example 7
Project: toshi-android-client   File: DirectoryService.java   View source code 6 votes vote down vote up
private DirectoryService() {
    final RxJavaCallAdapterFactory rxAdapter =
            RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io());
    final File cachePath = new File(BaseApplication.get().getCacheDir(), "dirCache");
    this.client = new OkHttpClient
            .Builder()
            .cache(new Cache(cachePath, 1024 * 1024 * 5))
            .addNetworkInterceptor(new ReadFromCacheInterceptor())
            .addInterceptor(new OfflineCacheInterceptor());

    addUserAgentHeader();
    addLogging();

    final Moshi moshi = new Moshi.Builder()
            .build();

    final Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BaseApplication.get().getResources().getString(R.string.directory_url))
            .addConverterFactory(MoshiConverterFactory.create(moshi))
            .addCallAdapterFactory(rxAdapter)
            .client(client.build())
            .build();
    this.directoryInterface = retrofit.create(DirectoryInterface.class);
}
 
Example 8
Project: toshi-android-client   File: ReputationService.java   View source code 6 votes vote down vote up
private ReputationService() {
    final RxJavaCallAdapterFactory rxAdapter = RxJavaCallAdapterFactory
            .createWithScheduler(Schedulers.io());
    final File cachePath = new File(BaseApplication.get().getCacheDir(), "repCache");
    this.client = new OkHttpClient
            .Builder()
            .cache(new Cache(cachePath, 1024 * 1024))
            .addNetworkInterceptor(new ReadFromCacheInterceptor())
            .addInterceptor(new OfflineCacheInterceptor());

    addSigningInterceptor();
    addUserAgentHeader();
    addLogging();

    final Moshi moshi = new Moshi
            .Builder()
            .build();

    final Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BaseApplication.get().getResources().getString(R.string.rep_url))
            .addConverterFactory(MoshiConverterFactory.create(moshi))
            .addCallAdapterFactory(rxAdapter)
            .client(client.build())
            .build();
    this.reputationInterface = retrofit.create(ReputationInterface.class);
}
 
Example 9
Project: toshi-android-client   File: CurrencyService.java   View source code 6 votes vote down vote up
private CurrencyService() {
    final RxJavaCallAdapterFactory rxAdapter = RxJavaCallAdapterFactory
            .createWithScheduler(Schedulers.io());
    final File cachePath = new File(BaseApplication.get().getCacheDir(), "ratesCache");
    this.client = new OkHttpClient
            .Builder()
            .cache(new Cache(cachePath, 1024 * 1024))
            .addNetworkInterceptor(new ReadFromCacheInterceptor())
            .addInterceptor(new OfflineCacheInterceptor());

    addUserAgentHeader();
    addLogging();

    final Moshi moshi = new Moshi.Builder()
            .add(new BigIntegerAdapter())
            .add(new BigDecimalAdapter())
            .build();

    final Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BaseApplication.get().getResources().getString(R.string.currency_url))
            .addConverterFactory(MoshiConverterFactory.create(moshi))
            .addCallAdapterFactory(rxAdapter)
            .client(client.build())
            .build();
    this.currencyInterface = retrofit.create(CurrencyInterface.class);
}
 
Example 10
Project: toshi-android-client   File: ChatService.java   View source code 6 votes vote down vote up
private ChatInterface generateSignalInterface() {
    final RxJavaCallAdapterFactory rxAdapter = RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io());

    addUserAgentHeader();
    addSigningInterceptor();
    addLogging();

    final Moshi moshi = new Moshi.Builder()
            .build();

    final Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(this.url)
            .addConverterFactory(ScalarsConverterFactory.create())
            .addConverterFactory(MoshiConverterFactory.create(moshi))
            .addCallAdapterFactory(rxAdapter)
            .client(client.build())
            .build();
    return retrofit.create(ChatInterface.class);
}
 
Example 11
Project: ProxerLibJava   File: ProxerApi.java   View source code 6 votes vote down vote up
private void initRetrofit() {
    final Retrofit.Builder builder;

    if (retrofit == null) {
        builder = new Retrofit.Builder();
    } else {
        builder = retrofit.newBuilder();
    }

    retrofit = builder.baseUrl(ProxerUrls.apiBase())
            .client(client)
            .addCallAdapterFactory(new ProxerResponseCallAdapterFactory())
            .addConverterFactory(MoshiConverterFactory.create(moshi))
            .addConverterFactory(new EnumRetrofitConverterFactory())
            .build();
}
 
Example 12
Project: Brockman   File: ApiModule.java   View source code 6 votes vote down vote up
private static Retrofit createRetrofit(String baseUrl, OkHttpClient okHttpClient) {
    if (okHttpClient == null) {
        okHttpClient = new OkHttpClient();
    }

    Moshi moshi = new Moshi.Builder()
            .add(new StreamTypeAdapter())
            .add(new StreamAdapter())
            .add(new VideoSizeAdapter())
            .build();

    return new Retrofit.Builder()
            .baseUrl(baseUrl)
            .addConverterFactory(MoshiConverterFactory.create(moshi))
            .client(okHttpClient)
            .build();
}
 
Example 13
Project: Iron   File: MainActivity.java   View source code 6 votes vote down vote up
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == R.id.action_settings) {
        Iron.chest().load(new Retrofit.Builder()
                .baseUrl("https://api.github.com")
                .addConverterFactory(MoshiConverterFactory.create())
                .build()
                .create(GitHubService.class)
                .listRepos("fabianterhorst"), Repo.class);
        return true;
    }

    return super.onOptionsItemSelected(item);
}
 
Example 14
Project: retroauth   File: RetroauthTest.java   View source code 6 votes vote down vote up
@Before
public void prepare() throws IOException {
    server = new MockWebServer();
    server.start();
    tokenStorage = new TestTokenStorage();
    MethodCache.DefaultMethodCache<String> methodCache = new MethodCache.DefaultMethodCache<>();
    AuthenticationHandler<String, String, String> authHandler =
            new AuthenticationHandler<>(
                    methodCache,
                    Mockito.mock(OwnerManager.class),
                    tokenStorage,
                    new TestProvider(),
                    new TestTokenTypeFactory()
            );

    Retrofit retrofit = new Retroauth.Builder<>(authHandler)
            .baseUrl(server.url("/"))
            .enableLocking(true)
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .addConverterFactory(MoshiConverterFactory.create())
            .build();

    service = retrofit.create(TestInterface.class);
}
 
Example 15
Project: rides-java-sdk   File: OAuth2ServiceTest.java   View source code 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    final HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
    loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);

    final OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .addInterceptor(loggingInterceptor)
            .build();

    final Moshi moshi = new Moshi.Builder().add(new OAuthScopesAdapter()).build();

    oAuth2Service = new Retrofit.Builder().baseUrl("http://localhost:" + wireMockRule.port())
            .client(okHttpClient)
            .addConverterFactory(MoshiConverterFactory.create(moshi))
            .build()
            .create(OAuth2Service.class);
}
 
Example 16
Project: analytics-android   File: E2ETest.java   View source code 6 votes vote down vote up
@Before
public void setup() {
  analytics = new Analytics.Builder(activityActivityTestRule.getActivity(), SEGMENT_WRITE_KEY)
      .build();

  runscopeService = new Retrofit.Builder()
      .baseUrl("https://api.runscope.com")
      .addConverterFactory(MoshiConverterFactory.create())
      .client(new OkHttpClient.Builder()
          .addNetworkInterceptor(new Interceptor() {
            @Override
            public okhttp3.Response intercept(Chain chain) throws IOException {
              return chain.proceed(chain.request()
                  .newBuilder()
                  .addHeader("Authorization", "Bearer " + RUNSCOPE_TOKEN)
                  .build());
            }
          })
          .build())
      .build()
      .create(RunscopeService.class);
}
 
Example 17
Project: GitHub   File: AnnotatedConverters.java   View source code 5 votes vote down vote up
public static void main(String... args) throws IOException {
  MockWebServer server = new MockWebServer();
  server.start();
  server.enqueue(new MockResponse().setBody("{\"name\": \"Moshi\"}"));
  server.enqueue(new MockResponse().setBody("{\"name\": \"Gson\"}"));
  server.enqueue(new MockResponse().setBody("<user name=\"SimpleXML\"/>"));
  server.enqueue(new MockResponse().setBody("{\"name\": \"Gson\"}"));

  com.squareup.moshi.Moshi moshi = new com.squareup.moshi.Moshi.Builder().build();
  com.google.gson.Gson gson = new GsonBuilder().create();
  MoshiConverterFactory moshiConverterFactory = MoshiConverterFactory.create(moshi);
  GsonConverterFactory gsonConverterFactory = GsonConverterFactory.create(gson);
  SimpleXmlConverterFactory simpleXmlConverterFactory = SimpleXmlConverterFactory.create();
  Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/"))
      .addConverterFactory(
          new AnnotatedConverterFactory.Builder().add(Moshi.class, moshiConverterFactory)
              .add(Gson.class, gsonConverterFactory)
              .add(SimpleXml.class, simpleXmlConverterFactory)
              .build())
      .addConverterFactory(gsonConverterFactory)
      .build();
  Service service = retrofit.create(Service.class);

  Library library1 = service.exampleMoshi().execute().body();
  System.out.println("Library 1: " + library1.name);

  Library library2 = service.exampleGson().execute().body();
  System.out.println("Library 2: " + library2.name);

  Library library3 = service.exampleSimpleXml().execute().body();
  System.out.println("Library 3: " + library3.name);

  Library library4 = service.exampleDefault().execute().body();
  System.out.println("Library 4: " + library4.name);

  server.shutdown();
}
 
Example 18
Project: GitHub   File: AnnotatedConverters.java   View source code 5 votes vote down vote up
public static void main(String... args) throws IOException {
  MockWebServer server = new MockWebServer();
  server.start();
  server.enqueue(new MockResponse().setBody("{\"name\": \"Moshi\"}"));
  server.enqueue(new MockResponse().setBody("{\"name\": \"Gson\"}"));
  server.enqueue(new MockResponse().setBody("<user name=\"SimpleXML\"/>"));
  server.enqueue(new MockResponse().setBody("{\"name\": \"Gson\"}"));

  com.squareup.moshi.Moshi moshi = new com.squareup.moshi.Moshi.Builder().build();
  com.google.gson.Gson gson = new GsonBuilder().create();
  MoshiConverterFactory moshiConverterFactory = MoshiConverterFactory.create(moshi);
  GsonConverterFactory gsonConverterFactory = GsonConverterFactory.create(gson);
  SimpleXmlConverterFactory simpleXmlConverterFactory = SimpleXmlConverterFactory.create();
  Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/"))
      .addConverterFactory(
          new AnnotatedConverterFactory.Builder().add(Moshi.class, moshiConverterFactory)
              .add(Gson.class, gsonConverterFactory)
              .add(SimpleXml.class, simpleXmlConverterFactory)
              .build())
      .addConverterFactory(gsonConverterFactory)
      .build();
  Service service = retrofit.create(Service.class);

  Library library1 = service.exampleMoshi().execute().body();
  System.out.println("Library 1: " + library1.name);

  Library library2 = service.exampleGson().execute().body();
  System.out.println("Library 2: " + library2.name);

  Library library3 = service.exampleSimpleXml().execute().body();
  System.out.println("Library 3: " + library3.name);

  Library library4 = service.exampleDefault().execute().body();
  System.out.println("Library 4: " + library4.name);

  server.shutdown();
}
 
Example 19
Project: YandexTranslator   File: ModelModule.java   View source code 5 votes vote down vote up
@Provides
@Singleton
Retrofit provideRetrofit(OkHttpClient client, MoshiConverterFactory converterFactory,
        RxJavaCallAdapterFactory adapterFactory) {
    return new Retrofit.Builder()
            .baseUrl(Config.BASE_URL)
            .addConverterFactory(converterFactory)
            .addCallAdapterFactory(adapterFactory)
            .client(client)
            .build();
}
 
Example 20
Project: IFTTTSDK-Android   File: IftttApiClient.java   View source code 5 votes vote down vote up
private IftttApiClient() {
    Moshi moshi = new Moshi.Builder().add(new HexColorJsonAdapter())
            .add(Date.class, new Rfc3339DateJsonAdapter().nullSafe())
            .add(new AppletJsonAdapter())
            .add(new AppletListJsonAdapter())
            .build();
    JsonAdapter<ErrorResponse> errorResponseJsonAdapter = moshi.adapter(ErrorResponse.class);

    tokenInterceptor = new TokenInterceptor();
    inviteCodeInterceptor = new InviteCodeInterceptor();
    OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(tokenInterceptor)
            .addInterceptor(inviteCodeInterceptor)
            .addInterceptor(new SdkInfoInterceptor())
            .build();
    Retrofit retrofit = new Retrofit.Builder().addConverterFactory(MoshiConverterFactory.create(moshi))
            .baseUrl("https://api.ifttt.com")
            .client(okHttpClient)
            .build();

    RetrofitAppletConfigApi retrofitAppletConfigApi = retrofit.create(RetrofitAppletConfigApi.class);
    appletConfigApi = new InternalAppletConfigApi(retrofitAppletConfigApi, errorResponseJsonAdapter);

    RetrofitAppletsApi retrofitAppletsApi = retrofit.create(RetrofitAppletsApi.class);
    appletsApi = new InternalAppletsApi(retrofitAppletsApi, errorResponseJsonAdapter);

    RetrofitUserApi retrofitUserApi = retrofit.create(RetrofitUserApi.class);
    userApi = new InternalUserApi(retrofitUserApi, errorResponseJsonAdapter);
}
 
Example 21
Project: BuildingDebugFeatures   File: NetworkModule.java   View source code 5 votes vote down vote up
@Provides
Retrofit.Builder retrofitBuilder(OkHttpClient.Builder okHttpClientBuilder) {
    Retrofit.Builder builder = new Retrofit.Builder()
            .baseUrl(baseUrl)
            .addConverterFactory(MoshiConverterFactory.create(new Moshi.Builder().build()))
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .client(okHttpClientBuilder.build());
    return builder;
}
 
Example 22
Project: .samples   File: KitsuRestApi.java   View source code 5 votes vote down vote up
private KitsuRestApi() {
    final Retrofit retrofit = (new Retrofit.Builder())
            .baseUrl("https://kitsu.io/api/edge/")
            .addConverterFactory(MoshiConverterFactory.create())
            .build();
    kitsuApi = retrofit.create(KitsuSpecApi.class);
}
 
Example 23
Project: osc   File: CameraClient.java   View source code 5 votes vote down vote up
CameraClient(String basePath) {
  Retrofit retrofit = new Retrofit.Builder()
      .baseUrl(basePath)
      .addConverterFactory(MoshiConverterFactory.create())
      .build();

  service = retrofit.create(CameraService.class);
}
 
Example 24
Project: superglue   File: ApiModule.java   View source code 5 votes vote down vote up
@Provides @Singleton Retrofit provideRetrofit(HttpUrl baseUrl, @Named("Api") OkHttpClient client,
    Moshi moshi) {
  return new Retrofit.Builder() //
      .client(client) //
      .baseUrl(baseUrl) //
      .addConverterFactory(MoshiConverterFactory.create(moshi)) //
      .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) //
      .build();
}
 
Example 25
Project: superglue   File: ApiModule.java   View source code 5 votes vote down vote up
@Provides @Singleton Retrofit provideRetrofit(HttpUrl baseUrl, @Named("Api") OkHttpClient client,
    Moshi moshi) {
  return new Retrofit.Builder() //
      .client(client) //
      .baseUrl(baseUrl) //
      .addConverterFactory(MoshiConverterFactory.create(moshi)) //
      .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) //
      .build();
}
 
Example 26
Project: android-banklink   File: NetworkModule.java   View source code 5 votes vote down vote up
@Provides
@Singleton
Retrofit provideRetrofit(OkHttpClient client) {
  return new Retrofit.Builder()
      .client(client)
      .baseUrl(SIGN_ENDPOINT)
      .addConverterFactory(ScalarsConverterFactory.create())
      .addConverterFactory(MoshiConverterFactory.create())
      .addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io()))
      .build();
}
 
Example 27
Project: DuckDuckDefine-Android   File: NetworkModule.java   View source code 5 votes vote down vote up
/**
 * Provide instance of Retrofit, utilising Moshi as the JSON converter to connect
 * to the DuckDuckGoAPI
 *
 * @param baseUrl HttpUrl instance
 * @param client OkHttpClient instance
 * @param moshi Moshi instance
 * @return Instance of Retrofit
 */
@Provides @Singleton
Retrofit provideRetrofit(HttpUrl baseUrl, OkHttpClient client, Moshi moshi) {
    return new Retrofit.Builder()
            .client(client)
            .baseUrl(baseUrl)
            .addConverterFactory(MoshiConverterFactory.create(moshi))
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build();
}
 
Example 28
Project: AndelaTrackChallenge   File: ApiClient.java   View source code 5 votes vote down vote up
public static Retrofit getClient() {
    if (retrofit == null) {
        retrofit = new Retrofit.Builder()
                .baseUrl(URLs.BASE_URL)
                .client(getOkClient())
                .addConverterFactory(MoshiConverterFactory.create(getMoshi()))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
    }
    return retrofit;
}
 
Example 29
Project: DaggerPresentation   File: AppModule.java   View source code 5 votes vote down vote up
@Provides
@ApplicationScope
Retrofit providesRetrofit() {
    File cacheFile = new File(mApplication.getCacheDir(), "okhttp_log");
    cacheFile.mkdir();

    Cache cache = new Cache(cacheFile, MAX_CACHE_SIZE);

    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
    loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

    OkHttpClient client = new OkHttpClient.Builder()
            .addInterceptor(loggingInterceptor)
            .addInterceptor(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    HttpUrl newRequestUrl = chain.request().url().newBuilder()
                            .addQueryParameter("api_key", "cc98251169b8b9895710b692b07790d7")
                            .addQueryParameter("format", "json")
                            .addQueryParameter("nojsoncallback", String.valueOf(1))
                            .build();
                    return chain.proceed(
                            chain.request().newBuilder().url(newRequestUrl).build());
                }
            })
            .cache(cache)
            .build();

    String baseUrl = mApplication.getString(R.string.flickr_api_base_url);
    Retrofit retrofit = new Retrofit.Builder()
            .addConverterFactory(MoshiConverterFactory.create())
            .baseUrl(String.valueOf(Html.fromHtml(baseUrl)))
            .client(client)
            .addCallAdapterFactory(
                    RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io()))
            .build();

    return retrofit;
}
 
Example 30
Project: pact-workshop-android   File: NetworkModule.java   View source code 5 votes vote down vote up
@VisibleForTesting
public Retrofit getRetrofit(@NonNull Context context,
                            @NonNull String baseUrl) {
  return new Retrofit.Builder()
      .baseUrl(baseUrl)
      .client(getOkHttpClient(context))
      .addConverterFactory(MoshiConverterFactory.create(getMoshi()))
      .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
      .build();
}
 
Example 31
Project: droidconde-2016   File: ApiModule.java   View source code 5 votes vote down vote up
@Provides @Singleton Retrofit provideRetrofit(OkHttpClient client, Moshi moshi, ApiEndpoint endpoint) {
    return new Retrofit.Builder()
            .client(client)
            .baseUrl(endpoint.url)
            .addConverterFactory(MoshiConverterFactory.create(moshi))
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .build();
}
 
Example 32
Project: devfestnantes-2016   File: ApiModule.java   View source code 5 votes vote down vote up
@Provides @Singleton Retrofit provideRetrofit(OkHttpClient client, Moshi moshi, ApiEndpoint endpoint) {
    return new Retrofit.Builder()
            .client(client)
            .baseUrl(endpoint.url)
            .addConverterFactory(MoshiConverterFactory.create(moshi))
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .build();
}
 
Example 33
Project: office365-and-azure-ad-grouper-provisioner   File: Office365ChangeLogConsumer.java   View source code 5 votes vote down vote up
public Office365ChangeLogConsumer() {
    // TODO: this.getConsumerName() isn't working for some reason. track down
    String name = this.getConsumerName() != null ? this.getConsumerName() : "o365";
    this.clientId = GrouperLoaderConfig.retrieveConfig().propertyValueStringRequired(CONFIG_PREFIX + name + ".clientId");
    this.clientSecret = GrouperLoaderConfig.retrieveConfig().propertyValueStringRequired(CONFIG_PREFIX + name + ".clientSecret");
    this.tenantId = GrouperLoaderConfig.retrieveConfig().propertyValueStringRequired(CONFIG_PREFIX + name + ".tenantId");
    this.scope = GrouperLoaderConfig.retrieveConfig().propertyValueString(CONFIG_PREFIX + name + ".scope", "https://graph.microsoft.com/.default");

    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
    loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

    OkHttpClient client = new OkHttpClient.Builder()
            .addInterceptor(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request request = chain.request().newBuilder().header("Authorization", "Bearer " + token).build();
                    return chain.proceed(request);
                }
            })
            .addInterceptor(loggingInterceptor)
            .build();
    Retrofit retrofit = new Retrofit
            .Builder()
            .baseUrl("https://graph.microsoft.com/v1.0/")
            .addConverterFactory(MoshiConverterFactory.create())
            .client(client)
            .build();

    this.service = retrofit.create(Office365GraphApiService.class);

    this.grouperSession = GrouperSession.startRootSession();
}
 
Example 34
Project: office365-and-azure-ad-grouper-provisioner   File: Office365ChangeLogConsumer.java   View source code 5 votes vote down vote up
private String getToken() throws IOException {
    logger.debug("Token client ID: " + this.clientId);
    logger.debug("Token tenant ID: " + this.tenantId);
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://login.microsoftonline.com/" + this.tenantId + "/")
            .addConverterFactory(MoshiConverterFactory.create())
            .build();
    Office365AuthApiService service = retrofit.create(Office365AuthApiService.class);
    retrofit2.Response<OAuthTokenInfo> response = service.getOauth2Token(
            "client_credentials",
            this.clientId,
            this.clientSecret,
            this.scope,
            "https://graph.microsoft.com")
            .execute();
    if (response.isSuccessful()) {
        OAuthTokenInfo info = response.body();
        logger.debug("Token scope: " + info.scope);
        logger.debug("Token expiresIn: " + info.expiresIn);
        logger.debug("Token expiresOn: " + info.expiresOn);
        logger.debug("Token resource: " + info.resource);
        logger.debug("Token tokenType: " + info.tokenType);
        logger.debug("Token notBefore: " + info.notBefore);
        return info.accessToken;
    } else {
        ResponseBody errorBody = response.errorBody();
        throw new IOException("error requesting token (" + response.code() + "): " + errorBody.string());
    }
}
 
Example 35
Project: playbook-android-sortedlist   File: PagingActivity.java   View source code 5 votes vote down vote up
private void setupRetrofit() {
  Single<ArticleService> single = Single.fromCallable(new Callable<ArticleService>() {
    @Override public ArticleService call() throws Exception {
      server = ArticleServer.create();
      server.start();
      Moshi moshi = new Moshi.Builder().add(ArticleJsonFactory.create()).build();
      Retrofit retrofit =
          new Retrofit.Builder().addConverterFactory(MoshiConverterFactory.create(moshi))
              .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
              .baseUrl(server.baseUrl())
              .build();
      return retrofit.create(ArticleService.class);
    }
  });

  single.subscribeOn(Schedulers.io())
      .delay(1, TimeUnit.SECONDS)
      .observeOn(AndroidSchedulers.mainThread())
      .subscribe(new DisposableSingleObserver<ArticleService>() {
        @Override public void onSuccess(ArticleService service) {
          Timber.d("Article service is created");
          articleService = service;
          handleServerReady();
        }

        @Override public void onError(Throwable throwable) {
          Timber.d(throwable, "Article service creation failed");
        }
      });
}
 
Example 36
Project: mobilization-2016   File: ApiModule.java   View source code 5 votes vote down vote up
@Provides @Singleton Retrofit provideRetrofit(OkHttpClient client, Moshi moshi, ApiEndpoint endpoint) {
    return new Retrofit.Builder()
            .client(client)
            .baseUrl(endpoint.url)
            .addConverterFactory(MoshiConverterFactory.create(moshi))
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .build();
}
 
Example 37
Project: droidconat-2016   File: ApiModule.java   View source code 5 votes vote down vote up
@Provides @Singleton Retrofit provideRetrofit(OkHttpClient client, Moshi moshi, ApiEndpoint endpoint) {
    return new Retrofit.Builder()
            .client(client)
            .baseUrl(endpoint.url)
            .addConverterFactory(MoshiConverterFactory.create(moshi))
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .build();
}
 
Example 38
Project: devoxxfr-2016   File: ApiModule.java   View source code 5 votes vote down vote up
@Provides @Singleton Retrofit provideRetrofit(OkHttpClient client, Moshi moshi, ApiEndpoint endpoint) {
    return new Retrofit.Builder()
            .client(client)
            .baseUrl(endpoint.url)
            .addConverterFactory(MoshiConverterFactory.create(moshi))
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .build();
}
 
Example 39
Project: droidcongr-2016   File: ApiModule.java   View source code 5 votes vote down vote up
@Provides @Singleton Retrofit provideRetrofit(OkHttpClient client, Moshi moshi, ApiEndpoint endpoint) {
    return new Retrofit.Builder()
            .client(client)
            .baseUrl(endpoint.url)
            .addConverterFactory(MoshiConverterFactory.create(moshi))
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .build();
}
 
Example 40
Project: wallabag-api-wrapper   File: WallabagService.java   View source code 5 votes vote down vote up
public WallabagService(String apiBaseURL, ParameterHandler parameterHandler, OkHttpClient okHttpClient) {
	nonEmptyString(apiBaseURL, "apiBaseURL");
	if(parameterHandler == null) {
		throw new NullPointerException("parameterHandler is null");
	}

	if(!apiBaseURL.endsWith("/")) apiBaseURL += "/";

	this.apiBaseURL = apiBaseURL;
	this.parameterHandler = parameterHandler;

	if(okHttpClient == null) okHttpClient = new OkHttpClient();

	wallabagAuthService = new Retrofit.Builder()
			.addConverterFactory(MoshiConverterFactory.create())
			.client(okHttpClient)
			.baseUrl(apiBaseURL)
			.build()
			.create(WallabagAuthService.class);

	okHttpClient = okHttpClient.newBuilder().addInterceptor(new TokenRefreshingInterceptor()).build();

	wallabagApiService = new Retrofit.Builder()
			.addConverterFactory(MoshiConverterFactory.create(
					new Moshi.Builder()
							.add(new NumericBooleanAdapter())
							.add(Date.class, new Rfc3339DateJsonAdapter())
							.build()))
			.client(okHttpClient)
			.baseUrl(apiBaseURL)
			.build()
			.create(WallabagApiService.class);
}