retrofit.client.OkClient Java Examples

The following examples show how to use retrofit.client.OkClient. 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: AppModule.java    From wear-notify-for-reddit with Apache License 2.0 6 votes vote down vote up
@Provides @Singleton public RedditService provideRedditService(Gson gson, Resources resources,
                                                               UserStorage userStorage,
                                                               TokenStorage tokenStorage,
                                                               RedditAuthenticationService authService) {
    final GsonConverter gsonConverter = new GsonConverter(gson);

    final OkHttpClient okHttpClient = new OkHttpClient();

    RedditService authenticatedRedditService = new RestAdapter.Builder().setEndpoint(Constants.ENDPOINT_URL_OAUTH_REDDIT)
            .setClient(new OkClient(okHttpClient))
            .setConverter(new DelegatingConverter(gsonConverter,
                    new TokenConverter(gsonConverter),
                    new PostConverter(gsonConverter, resources, userStorage, new HtmlDecoder()),
                    new MarkAsReadConverter(),
                    new SubscriptionConverter(),
                    new CommentsConverter(gson, gsonConverter, resources, userStorage)))
            .build()
            .create(RedditService.class);

    okHttpClient.networkInterceptors()
            .add(new TokenRefreshInterceptor(tokenStorage, authService));
    okHttpClient.setRetryOnConnectionFailure(true);
    return authenticatedRedditService;
}
 
Example #2
Source File: RestServiceFactory.java    From Muzesto with GNU General Public License v3.0 6 votes vote down vote up
public static <T> T create(final Context context, String baseUrl, Class<T> clazz) {
    final OkHttpClient okHttpClient = new OkHttpClient();

    okHttpClient.setCache(new Cache(context.getApplicationContext().getCacheDir(),
            CACHE_SIZE));
    okHttpClient.setConnectTimeout(40, TimeUnit.SECONDS);

    RequestInterceptor interceptor = new RequestInterceptor() {
        @Override
        public void intercept(RequestFacade request) {
            //7-days cache
            request.addHeader("Cache-Control", String.format("max-age=%d,max-stale=%d", Integer.valueOf(60 * 60 * 24 * 7), Integer.valueOf(31536000)));
            request.addHeader("Connection", "keep-alive");
        }
    };

    RestAdapter.Builder builder = new RestAdapter.Builder()
            .setEndpoint(baseUrl)
            .setRequestInterceptor(interceptor)
            .setClient(new OkClient(okHttpClient));

    return builder
            .build()
            .create(clazz);

}
 
Example #3
Source File: RetroInterface.java    From Expert-Android-Programming with MIT License 6 votes vote down vote up
private static RestAdapter getImageApiAdapter() {

        RequestInterceptor requestInterceptor = new RequestInterceptor() {
            @Override
            public void intercept(RequestFacade request) {
                request.addHeader(Constant.TAG_TOKEN, Constant.APP_TOKEN);
            }
        };

        return new RestAdapter.Builder()
                .setLogLevel(LOG_LEVEL)
                .setEndpoint(RetroInterface.TARGET_URL)
                .setRequestInterceptor(requestInterceptor)
                .setClient(new OkClient(new OkHttpClient()))
                .build();
    }
 
Example #4
Source File: RetroInterface.java    From Expert-Android-Programming with MIT License 6 votes vote down vote up
private static RestAdapter getRestAdapter() {

        RequestInterceptor requestInterceptor = new RequestInterceptor() {
            @Override
            public void intercept(RequestFacade request) {
                request.addHeader(Constant.TAG_TOKEN, Constant.APP_TOKEN);
            }
        };

        return new RestAdapter.Builder()
                .setLogLevel(LOG_LEVEL)
                .setEndpoint(RetroInterface.TARGET_URL)
                .setRequestInterceptor(requestInterceptor)
                .setClient(new OkClient(new OkHttpClient()))
                .build();
    }
 
Example #5
Source File: ConnectivityAwereUrlClientTest.java    From MVPAndroidBootstrap with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    ShadowLog.stream = System.out;

    mockWebServer = new MockWebServer();
    mockWebServer.start(9999);

    baseRetryHandler = BaseRetryHandler_.getInstance_(RuntimeEnvironment.application);
    connectivityAwareUrlClient = ConnectivityAwareUrlClient_.getInstance_(RuntimeEnvironment.application);
    connectivityAwareUrlClient.setWrappedClient(new OkClient(new OkHttpClient()));
    connectivityAwareUrlClient.setRetryHandler(baseRetryHandler);


    RestAdapter restAdapter = new RestAdapter.Builder()
            .setClient(connectivityAwareUrlClient)
            .setLogLevel(RestAdapter.LogLevel.FULL)
            .setEndpoint(mockWebServer.getUrl("/").toString()).build();

    sodaService = restAdapter.create(SodaService.class);
}
 
Example #6
Source File: WorkingWithRetrofitTest.java    From rxsnappy with Apache License 2.0 6 votes vote down vote up
@Override
protected void setUp() throws Exception {
    super.setUp();
    RxSnappy.init(getContext());
    mockWebServer = new MockWebServer();
    mockWebServer.start(9812);

    OkHttpClient okHttpClient = new OkHttpClient();
    RestAdapter restAdapter = new RestAdapter.Builder()
            .setClient(new OkClient(okHttpClient))
            .setEndpoint(mockWebServer.getUrl("/").toString())
            .build();

    testRestAdapter = restAdapter.create(TestRestAdapter.class);

    rxSnappyClient = new RxSnappyClient();
}
 
Example #7
Source File: DrupalOAuth2Manager.java    From drupalfit with MIT License 6 votes vote down vote up
public DrupalOAuth2Manager(Context context, String endpoint, String clientId, String clientSecret) {
    setContext(context);
    setEndpoint(endpoint);
    setClientId(clientId);
    setClientSecret(clientSecret);

    Client client = new OkClient(getOkHttpClient());

    if (mRequestInterceptor == null) {
        mRequestInterceptor = new SimpleRequestInterceptor();
    }
    mRequestInterceptor.cookie = cookie;

    RestAdapter restAdapter = new RestAdapter.Builder()
        .setEndpoint(endpoint)
        .setRequestInterceptor(mRequestInterceptor)
        .setErrorHandler(new ErrorHandler())
        .setClient(client)
        .setConverter(new retrofit.converter.JacksonConverter())
        .build();

    mService = restAdapter.create(DrupalOAuth2.class);
}
 
Example #8
Source File: DrupalManager.java    From drupalfit with MIT License 6 votes vote down vote up
public DrupalService getService(String endpoint) {
    if (endpoint == null) return mService;

    if (mService == null) {
        this.endpoint = endpoint;
        Client client = new OkClient(getOkHttpClient());

        if (mRequestInterceptor == null) {
            mRequestInterceptor = new SimpleRequestInterceptor();
        }
        mRequestInterceptor.cookie = cookie;
        mRequestInterceptor.accessToken = accessToken;
        mRequestInterceptor.xcsrfToken = xcsrfToken;

        mService = new RestAdapter.Builder()
            .setEndpoint(endpoint)
            .setRequestInterceptor(mRequestInterceptor)
            .setErrorHandler(new ErrorHandler())
            .setClient(client)
            .setConverter(new retrofit.converter.JacksonConverter())
            .setLogLevel(RestAdapter.LogLevel.FULL)  // Do this for development too.
            .build().create(DrupalService.class);
    }

    return mService;
}
 
Example #9
Source File: AuthServerHelper.java    From divide with Apache License 2.0 6 votes vote down vote up
private TestService buildTestService(String url){
    if(testService==null){
        RestAdapter restAdapter = new RestAdapter.Builder()
                .setClient( new OkClient() )
                .setEndpoint(url)
                .setLogLevel(RestAdapter.LogLevel.FULL)
                .setLog(new RestAdapter.Log() {
                    @Override
                    public void log(String s) {
                        System.out.println(s);
                    }
                }).build();

        testService = restAdapter.create(TestService.class);
    }
    return testService;
}
 
Example #10
Source File: ApiClient.java    From githot with Apache License 2.0 5 votes vote down vote up
/**
 * 用于Stethoscope调试的ttpClient
 */
public static OkClient getOkClient() {
    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
    client.setReadTimeout(READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
    client.networkInterceptors().add(new StethoInterceptor());
    return new OkClient(client);
}
 
Example #11
Source File: DataModule.java    From githot with Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
FirService provideFirService(Gson gson, OkHttpClient okHttpClient, ErrorHandler errorHandler) {
    RestAdapter restAdapter = new RestAdapter.Builder()
            .setErrorHandler(errorHandler)
            .setClient(new OkClient(okHttpClient))
            .setConverter(new GsonConverter(gson))
            .setLogLevel(RestAdapter.LogLevel.BASIC)
            .setEndpoint("http://api.fir.im")
            .build();
    return restAdapter.create(FirService.class);
}
 
Example #12
Source File: DataModule.java    From githot with Apache License 2.0 5 votes vote down vote up
@Provides
    @Singleton
    RestAdapter provideRestAdapter(Gson gson, OkHttpClient okHttpClient, ErrorHandler errorHandler) {
        return new RestAdapter.Builder()
                .setErrorHandler(errorHandler)
                .setClient(new OkClient(okHttpClient))
                .setConverter(new GsonConverter(gson))
                .setLogLevel(RestAdapter.LogLevel.BASIC)
//                .setEndpoint("http://mock-api.com/TyTabSFqXNyqMpNw.mock")
                .setEndpoint("https://api.github.com")
                .build();
    }
 
Example #13
Source File: ApiFactory.java    From particle-android with Apache License 2.0 5 votes vote down vote up
private RestAdapter.Builder buildCommonRestAdapterBuilder(Gson gson, OkHttpClient client) {
    return new RestAdapter.Builder()
            .setClient(new OkClient(client))
            .setConverter(new GsonConverter(gson))
            .setEndpoint(getApiUri().toString())
            .setLogLevel(httpLogLevel);
}
 
Example #14
Source File: TimeoutClientProvider.java    From infobip-api-java-client with Apache License 2.0 5 votes vote down vote up
@Override
public Client get() {
	final OkHttpClient okHttpClient = new OkHttpClient();
	okHttpClient.setReadTimeout(configuration.getReadTimeout(), TimeUnit.MILLISECONDS);
	okHttpClient.setConnectTimeout(configuration.getConnectionTimeout(), TimeUnit.MILLISECONDS);
	return new OkClient(okHttpClient);
}
 
Example #15
Source File: AcronymOps.java    From mobilecloud-15 with Apache License 2.0 5 votes vote down vote up
/**
 * Hook method dispatched by the GenericActivity framework to
 * initialize the AcronymOps object after it's been created.
 *
 * @param view         The currently active AcronymOps.View.
 * @param firstTimeIn  Set to "true" if this is the first time the
 *                     Ops class is initialized, else set to
 *                     "false" if called after a runtime
 *                     configuration change.
 */
public void onConfiguration(AcronymOps.View view,
                            boolean firstTimeIn) {
    Log.d(TAG,
          "onConfiguration() called");

    // Reset the mAcronymView WeakReference.
    mAcronymView =
        new WeakReference<>(view);

    if (firstTimeIn) {
        // Store the Application context to avoid problems with
        // the Activity context disappearing during a rotation.
        mContext = view.getApplicationContext();
    
        // Set up the HttpResponse cache that will be used by
        // Retrofit.
        mCache = new Cache(new File(mContext.getCacheDir(),
                                    CACHE_FILENAME),
                           // Cache stores up to 1 MB.
                           1024 * 1024); 
    
        // Set up the client that will use this cache.  Retrofit
        // will use okhttp client to make network calls.
        mOkHttpClient = new OkHttpClient();  
        if (mCache != null) 
            mOkHttpClient.setCache(mCache);

        // Create a proxy to access the Acronym Service web
        // service.
        mAcronymWebServiceProxy =
            new RestAdapter.Builder()
            .setEndpoint(AcronymWebServiceProxy.ENDPOINT)
            .setClient(new OkClient(mOkHttpClient))
            // .setLogLevel(LogLevel.FULL)
            .setLogLevel(LogLevel.NONE)
            .build()
            .create(AcronymWebServiceProxy.class);
    } 
}
 
Example #16
Source File: ApiFactory.java    From spark-sdk-android with Apache License 2.0 5 votes vote down vote up
private RestAdapter.Builder buildCommonRestAdapterBuilder(Gson gson, OkHttpClient client) {
    return new RestAdapter.Builder()
            .setClient(new OkClient(client))
            .setConverter(new GsonConverter(gson))
            .setEndpoint(getApiUri().toString())
            .setLogLevel(LogLevel.valueOf(ctx.getString(R.string.http_log_level)));
}
 
Example #17
Source File: Constants.java    From Mover with Apache License 2.0 5 votes vote down vote up
public static void init(Context context){
    //TODO initialize singletons or global instance of class
    Configuration config = new Configuration.Builder(context)
            .injector((WatchMeApplication) context)
            .build();

    sJobManager = new JobManager(context, config);

    sOkHttpClient = new OkHttpClient();
    sOkClient = new OkClient(sOkHttpClient);

    sEventBus = new Bus();
}
 
Example #18
Source File: RestClientFactory.java    From echo with Apache License 2.0 5 votes vote down vote up
public Client getClient(Boolean insecure) {
  if (insecure) {
    return new OkClient(httpClientFactory.getInsecureClient());
  } else {
    return new OkClient();
  }
}
 
Example #19
Source File: OkClientModule.java    From hacker-news-android with Apache License 2.0 5 votes vote down vote up
@Provides
@Named("okclient")
OkClient providesOkClient(){
    OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.setFollowRedirects(true);
    okHttpClient.setFollowSslRedirects(true);

    if(mInterceptorList != null){
        okHttpClient.networkInterceptors().addAll(mInterceptorList);
    }

    okHttpClient.networkInterceptors().add(new StethoInterceptor());

    return new OkClient(okHttpClient);
}
 
Example #20
Source File: NetworkServiceModule.java    From hacker-news-android with Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
HackerNewsService provideService(@Named("retrofit-loglevel") RestAdapter.LogLevel logLevel,
                                 @Named("loganSquare") LoganSquareConvertor loganSquareConvertor,
                                 @Named("okclient") OkClient okClient) {
    return new RestAdapter.Builder()
            .setConverter(loganSquareConvertor)
            .setLogLevel(logLevel)
            .setClient(okClient)
            .setEndpoint("https://whispering-fortress-7282.herokuapp.com/")
            .build()
            .create(HackerNewsService.class);
}
 
Example #21
Source File: NetworkServiceModule.java    From hacker-news-android with Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
LoginService providesLoginService(@Named("retrofit-loglevel") RestAdapter.LogLevel logLevel,
                                  @Named("loganSquare") LoganSquareConvertor loganSquareConvertor,
                                  @Named("okclient") OkClient okClient) {
    return new RestAdapter.Builder()
            .setClient(okClient)
            .setLogLevel(logLevel)
            .setConverter(loganSquareConvertor)
            .setEndpoint("https://news.ycombinator.com")
            .build()
            .create(LoginService.class);
}
 
Example #22
Source File: NetworkServiceModule.java    From hacker-news-android with Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
UserService providesUserService(@Named("retrofit-loglevel") RestAdapter.LogLevel logLevel,
                                @Named("loganSquare") LoganSquareConvertor loganSquareConvertor,
                                @Named("okclient") OkClient okClient) {
    return new RestAdapter.Builder()
            .setClient(okClient)
            .setLogLevel(logLevel)
            .setConverter(loganSquareConvertor)
            .setEndpoint("https://news.ycombinator.com")
            .build()
            .create(UserService.class);
}
 
Example #23
Source File: AppApplication.java    From AppCodeArchitecture with Apache License 2.0 5 votes vote down vote up
private void setUpApiService() {
    Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new DateTypeAdapter()).create();
    OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.setConnectTimeout(15, TimeUnit.SECONDS);
    RestAdapter restAdapter = new RestAdapter.Builder()
            .setEndpoint(BuildConfig.API_HOST)
            .setConverter(new GsonConverter(gson))
            .setClient(new OkClient(okHttpClient))
            .build();
    sAppApiService = restAdapter.create(AppApiService.class);
}
 
Example #24
Source File: NetworkAPI.java    From example with Apache License 2.0 5 votes vote down vote up
public NetworkAPI() {
  OkHttpClient httpClient = new OkHttpClient();
  Gson gson = new GsonBuilder().create();

  RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(WEBSERVICE)
      .setLogLevel(BuildConfig.DEBUG ? RestAdapter.LogLevel.FULL : RestAdapter.LogLevel.NONE)
      .setClient(new OkClient(httpClient))
      .setConverter(new GsonConverter(gson))
      .build();

  service = restAdapter.create(PratamaService.class);
}
 
Example #25
Source File: InstagramService.java    From example with Apache License 2.0 5 votes vote down vote up
public InstagramService() {
  OkHttpClient client = new OkHttpClient();
  Gson gson = new Gson();

  RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(URL)
      .setLogLevel(BuildConfig.DEBUG ? RestAdapter.LogLevel.FULL : RestAdapter.LogLevel.NONE)
      .setClient(new OkClient(client))
      .setConverter(new GsonConverter(gson))
      .build();

  api = restAdapter.create(InstagramApi.class);
}
 
Example #26
Source File: TapchatModule.java    From tapchat-android with Apache License 2.0 5 votes vote down vote up
@Provides @Singleton @Named(PUSH) RestAdapter providePushRestAdapter(Gson gson, OkHttpClient okHttpClient) {
    return new RestAdapter.Builder()
        .setEndpoint("https://tapchat.herokuapp.com:443")
        .setConverter(new GsonConverter(gson, "UTF-8"))
        .setClient(new OkClient(okHttpClient))
        .build();
}
 
Example #27
Source File: TapchatModule.java    From tapchat-android with Apache License 2.0 5 votes vote down vote up
@Provides @Singleton public RestAdapter provideRestAdapter(Gson gson, OkHttpClient okHttpClient, TapchatSession session, TapchatRequestInterceptor requestInterceptor) {
    return new RestAdapter.Builder()
        .setEndpoint(session)
        .setConverter(new GsonConverter(gson, "UTF-8"))
        .setClient(new OkClient(okHttpClient))
        .setRequestInterceptor(requestInterceptor)
        .build();
}
 
Example #28
Source File: AbstractWebManager.java    From divide with Apache License 2.0 5 votes vote down vote up
private RestAdapter createRestAdapter(Config config){
    RestAdapter.Builder builder = new RestAdapter.Builder();
    builder.setClient( new OkClient( config.client ) )
        .setEndpoint(config.serverUrl)
        .setLogLevel(RestAdapter.LogLevel.FULL)
        .setLog(new RestAdapter.Log() {
            @Override
            public void log(String s) {
                retrologger.debug(s);
            }
        })
        .setConverter(new GsonConverter(new Gson()))
        .setRequestInterceptor(new RequestInterceptor() {
            @Override
            public void intercept(RequestFacade requestFacade) {
                onRequest(requestFacade);
            }
        })
        .setProfiler(new Profiler() {
            @Override
            public Object beforeCall() {
                return null;
            }

            @Override
            public void afterCall(RequestInformation requestInformation, long l, int i, Object o) {
                retrologger.error("afterCall(" + requestInformation.getRelativePath() + ":" + requestInformation.getMethod() + ": " + i + " : " + o);
                requestEventPublisher.onNext(new RequestObject(requestInformation,l,i,o));
            }
        });

    return builder.build();
}
 
Example #29
Source File: RetrofitClientFactory.java    From kayenta with Apache License 2.0 5 votes vote down vote up
public <T> T createClient(
    Class<T> type,
    Converter converter,
    RemoteService remoteService,
    OkHttpClient okHttpClient,
    String username,
    String password,
    String usernamePasswordFile)
    throws IOException {
  String baseUrl = remoteService.getBaseUrl();

  baseUrl = baseUrl.endsWith("/") ? baseUrl.substring(0, baseUrl.length() - 1) : baseUrl;

  Endpoint endpoint = newFixedEndpoint(baseUrl);

  if (!(StringUtils.isEmpty(username)
      && StringUtils.isEmpty(password)
      && StringUtils.isEmpty(usernamePasswordFile))) {
    okHttpClient = createAuthenticatedClient(username, password, usernamePasswordFile);
  }

  Slf4jRetrofitLogger logger = createRetrofitLogger.apply(type);

  return new RestAdapter.Builder()
      .setEndpoint(endpoint)
      .setClient(new OkClient(okHttpClient))
      .setConverter(converter)
      .setLogLevel(RestAdapter.LogLevel.valueOf(retrofitLogLevel))
      .setLog(logger)
      .build()
      .create(type);
}
 
Example #30
Source File: NetworkModule.java    From Dagger-2-Example with Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
public PokemonService provideService(Endpoint endpoint, @Named("HttpExecutor") Executor httpExecutor,
                                     @Named("CallbackExecutor") Executor callbackExecutor, OkHttpClient client,
                                     RestAdapter.Log log) {

    return new RestAdapter.Builder()
            .setClient(new OkClient(client))
            .setEndpoint(endpoint)
            .setLog(log)
            .setLogLevel(RestAdapter.LogLevel.FULL)
            .setExecutors(httpExecutor, callbackExecutor)
            .build().create(PokemonService.class);
}