Java 类retrofit.client.OkClient 实例源码

项目:owa-notifier    文件:RestfullAcessProxy.java   
/**
 * Return a instance of tokenService to call it
 * 
 * @param authority
 * @return TokenService return a proxy to call api
 */
private static TokenService getRealTokenService(String authority) {
    // Create a logging interceptor to log request and responses
    OkHttpClient client = new OkHttpClient();
    InetSocketAddress p = findProxy();
    if(p != null) {
        client.setProxy(new Proxy(Proxy.Type.HTTP,p));
    } else { 
        client.setProxy(Proxy.NO_PROXY); 
    }
    // Create and configure the Retrofit object
    RestAdapter retrofit = new RestAdapter.Builder().setEndpoint(authority)
            .setLogLevel(LogLevel.FULL).setLog(new RestAdapter.Log() {
                @Override
                public void log(String msg) {
                    logger.debug(msg);
                }
            }).setClient(new OkClient(client)).build();

    // Generate the token service
    return retrofit.create(TokenService.class);
}
项目:Expert-Android-Programming    文件:RetroInterface.java   
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();
    }
项目:Expert-Android-Programming    文件:RetroInterface.java   
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();
    }
项目:Muzesto    文件:RestServiceFactory.java   
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);

}
项目:fiat    文件:FiatAuthenticationConfig.java   
@Bean
@ConditionalOnMissingBean(FiatService.class) // Allows for override
public FiatService fiatService(FiatClientConfigurationProperties fiatConfigurationProperties,
                               SpinnakerRequestInterceptor interceptor,
                               OkClient okClient) {
  // New role providers break deserialization if this is not enabled.
  val objectMapper = new ObjectMapper();
  objectMapper.enable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL);
  objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
  return new RestAdapter.Builder()
      .setEndpoint(Endpoints.newFixedEndpoint(fiatConfigurationProperties.getBaseUrl()))
      .setRequestInterceptor(interceptor)
      .setClient(okClient)
      .setConverter(new JacksonConverter(objectMapper))
      .setLogLevel(retrofitLogLevel)
      .setLog(new Slf4jRetrofitLogger(FiatService.class))
      .build()
      .create(FiatService.class);
}
项目:simple-map-android    文件:ServiceBaseService.java   
ServiceBaseService() {

        final OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.setReadTimeout(30, TimeUnit.SECONDS);
        okHttpClient.setConnectTimeout(15, TimeUnit.SECONDS);
        okHttpClient.setRetryOnConnectionFailure(true);
        okHttpClient.setFollowRedirects(false);
        okHttpClient.interceptors().add(new ConnectionRetryInterceptor());

        RestAdapter mRestAdapter = new RestAdapter.Builder()
                .setEndpoint(ApiConnectionInterface.BASE_API_URL)
                .setClient(new OkClient(okHttpClient))
                .setLogLevel(RestAdapter.LogLevel.FULL).setLog(new RestAdapter.Log() {
                    @Override
                    public void log(String msg) {
                        Log.d("SIMPLE_MAP_APP", msg);
                    }
                })
                .build();

        mServiceInterface = mRestAdapter.create(ApiConnectionInterface.class);
    }
项目:edd-licensing-java-client    文件:EDDLicensingClientFactory.java   
/**
 * Creates a REST client.
 * @param url The URL of the EDD Licensing REST API endpoint.
 * @return A {@link EDDLicensingClient}.
 */
public static EDDLicensingClient createRestClient(String url) {

     Gson gson = new GsonBuilder()
                .setDateFormat("yyyy-MM-dd HH:mm:ss")
                .create();

    RestAdapter restAdapter = new RestAdapter.Builder()
               .setEndpoint(url)
               .setConverter(new GsonConverter(gson))
               .setClient(new OkClient(new OkHttpClient()))
               .build();

    EDDLicensingClient client = restAdapter.create(EDDLicensingClient.class);

    return client;

}
项目:smoothnovelreader    文件:BaiduBrowserNovelSource.java   
public BaiduBrowserNovelSource(OkHttpClient okHttpClient) {
    /*this.mOkHttpClient = new OkHttpClient();
    this.mOkHttpClient.setConnectTimeout(20, TimeUnit.SECONDS);
    this.mOkHttpClient.setWriteTimeout(20, TimeUnit.SECONDS);
    this.mOkHttpClient.setReadTimeout(20, TimeUnit.SECONDS);*/
    this.mNovelSource = new RestAdapter.Builder()
            .setRequestInterceptor(request -> {
                request.addHeader("User-Agent", "Mozilla/5.0 (Linux; Android 4.0.4; Galaxy Nexus Build/IMM76B) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.133 Mobile Safari/535.19");
                request.addHeader("Accept", "application/json,text/html");
            })
            .setEndpoint(BaiduBrowserService.BAIDU_BROWSER_NOVEL_URL)
            .setClient(new OkClient(okHttpClient))
            .setConverter(new CustomGsonConverter(new Gson()))
            .build()
            .create(BaiduBrowserService.class);
}
项目:apna-library    文件:ApiClient.java   
/**
 * Initializes the adapter and returns it
 * The REST Adapter is created with Retrofit methods defined in MainApiClient
 * Injects authorization headers into request
 * Inspects status codes from response
 * @return rest adapter
 */
private MainApiClient getRestAdapter() {

    httpClient = new OkHttpClient();
    httpClient.networkInterceptors().add(new StethoInterceptor());
    httpClient.interceptors().add(new Interceptor() {
        @Override
        public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            com.squareup.okhttp.Response response = chain.proceed(request);
            statusCode = response.code();
            return response;
        }
    });

    mRestAdapter = new RestAdapter.Builder()
            .setEndpoint(URL_UAT)
            .setClient(new OkClient(httpClient))
            .setRequestInterceptor(authHeader())
            .setLogLevel(RestAdapter.LogLevel.FULL)
            .build();

    return mRestAdapter.create(MainApiClient.class);
}
项目:msf_communique    文件:Auth.java   
/**
 * Function to authenticate any communication with the server.
 * @param username
 * @param password
 * @return The interface that verifies the authentication
 */
public static Interface getInterface(String username, String password) {
    String credentials = username+":"+password;
    RestAdapter.Builder builder = new RestAdapter.Builder()
            .setEndpoint(SERVER_URL)
            .setLogLevel(RestAdapter.LogLevel.FULL)
            .setClient(new OkClient(clientOkHttp));
    clientOkHttp.setReadTimeout(60, TimeUnit.SECONDS);
    clientOkHttp.setConnectTimeout(60, TimeUnit.SECONDS);

    // create Base64 encode string
    final String basic =
            "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);

    builder.setRequestInterceptor(new RequestInterceptor() {
        @Override
        public void intercept(RequestInterceptor.RequestFacade request) {
            request.addHeader("Authorization", basic);
            request.addHeader("Accept", "application/json");
        }
    });
    RestAdapter adapter = builder.build();
    Interface communicatorInterface = adapter.create(Interface.class);
    return communicatorInterface;
}
项目:influxdb-inflow    文件:DriverHTTP.java   
public DriverHTTP(final String uri, final String username, final String password, Client client) {
  Preconditions.checkArgument(!Strings.isNullOrEmpty(uri), "URI can not be null or empty");
  Preconditions.checkArgument(!Strings.isNullOrEmpty(username), "Username can not null or empty");

  this.uri = uri;
  this.username = username;
  this.password = password;

  if (this.client == null) {
    this.client = new OkClient(new OkHttpClient());
  } else {
    this.client = client;
  }

  this.restAdapter = new RestAdapter.Builder()
          .setEndpoint(this.uri)
          .setErrorHandler(new InfluxDBHTTPErrorHandler())
          .setClient(this.client)
          .build();
  this.restService = this.restAdapter.create(InfluxDBHTTPInterface.class);
}
项目:influxdb-inflow    文件:Client.java   
public Client(String host, int port, String username, String password, boolean useHttps, boolean verifySSL, int timeout) {
  this.host = host;
  this.port = port;
  this.username = username;
  this.password = password;
  this.timeout = timeout;
  this.verifySSL = verifySSL;

  if (useHttps) {
    this.scheme = "https";
  }

  // the the base URI
  this.baseURI = String.format("%s://%s:%d", this.scheme, this.host, this.port);

  // set the default driver to HTTP
  OkHttpClient okHttpClient = new OkHttpClient();
  okHttpClient.setReadTimeout(timeout, TimeUnit.SECONDS);
  // TODO: how to enforce verifySSL with OkHttpClient ?
  OkClient okClient = new OkClient(okHttpClient);
  this.driver = new DriverHTTP(this.baseURI, this.username, this.password, okClient);

  this.admin = new Admin(this);
}
项目:MVPAndroidBootstrap    文件:ConnectivityAwereUrlClientTest.java   
@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);
}
项目:rxsnappy    文件:WorkingWithRetrofitTest.java   
@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();
}
项目:uphold-sdk-android    文件:UpholdRestAdapter.java   
/**
 * Constructor.
 */

public UpholdRestAdapter() {
    OkHttpClient okHttpClient = new OkHttpClient();

    try {
        okHttpClient.setSslSocketFactory(new TLSV12SSLSocketFactory());
    } catch (NoSuchAlgorithmException | KeyManagementException exception) {
        exception.printStackTrace();
    }

    this.adapter = new RestAdapter.Builder().setEndpoint(BuildConfig.API_SERVER_URL)
        .setClient(new OkClient(okHttpClient))
        .setErrorHandler(new UpholdRetrofitErrorHandling())
        .setLogLevel(BuildConfig.DEBUG ? RestAdapter.LogLevel.FULL : RestAdapter.LogLevel.NONE)
        .setRequestInterceptor(getUpholdRequestInterceptor())
        .build();
}
项目:tuchong-daily-android    文件:APIFactory.java   
public static API instance() {
    if (instance == null) {
        OkHttpClient client = new OkHttpClient();
        if (BuildConfig.DEBUG) {
            client.networkInterceptors().add(new StethoInterceptor());
        }

        RestAdapter restAdapter = new RestAdapter.Builder()
                .setEndpoint(BASE_URL)
                .setClient(new OkClient(client))
                .setLogLevel(RestAdapter.LogLevel.FULL)
                .build();
        instance = new API(restAdapter.create(APIGet.class));
    }
    return instance;
}
项目:AppStructure    文件:RetrofitComponent.java   
public static <T> T buildService(Class<T> servie){
    if(mRestAdapter == null){
        synchronized (RetrofitComponent.class){
            if(mRestAdapter == null){
                RestAdapter.Builder builder = new RestAdapter.Builder();
                builder.setClient(new OkClient(OkHttpComponent.build()));
                builder.setConverter(new GsonConverter(GsonComponent.build()));
                builder.setEndpoint(Endpoints.newFixedEndpoint(AppStructure.getInstance().getServer()));
                builder.setLogLevel(AppStructure.isDebug() ? RestAdapter.LogLevel.FULL : RestAdapter.LogLevel.NONE);
                mRestAdapter = builder.build();
                if(AppStructure.isDebug()){
                    TLog.i(LOG_TAG,"RetrofitComponent initialize!");
                }
            }
        }
    }
    return mRestAdapter.create(servie);
}
项目:intercom-android-sdk    文件:IntercomClient.java   
public IntercomClient(Intercom intercom) {
  Gson gson = getAPIGsonRegistry();

  OkHttpClient okHttpClient = new OkHttpClient();
  okHttpClient.setConnectTimeout(CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
  okHttpClient.setReadTimeout(READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);

  BasicAuthProvider authProvider = new BasicAuthProvider(intercom.getAPP_ID(), intercom.getAPI_KEY());

  intercomApi = new RestAdapter.Builder()
      .setEndpoint(AppConstants.API_HOST)
      .setClient(new OkClient(okHttpClient))
      .setLogLevel(BuildConfig.DEBUG ? RestAdapter.LogLevel.FULL : RestAdapter.LogLevel.NONE)
      .setConverter(new GsonConverter(gson))
      .setRequestInterceptor(authProvider)
      .build();

  userService = intercomApi.create(Users.class);
}
项目:cusnews    文件:Api.java   
/**
 * Init the http-client and cache.
 */
private static void initClient( Context cxt ) {
    // Create an HTTP client that uses a cache on the file system. Android applications should use
    // their Context to get a cache directory.
    OkHttpClient okHttpClient = new OkHttpClient();
    //      okHttpClient.networkInterceptors().add(new StethoInterceptor());

    File cacheDir = new File(
            cxt != null ? cxt.getCacheDir().getAbsolutePath() : System.getProperty( "java.io.tmpdir" ), UUID.randomUUID().toString() );
    try {
        sCache = new com.squareup.okhttp.Cache( cacheDir, sCacheSize );
    } catch( IOException e ) {
        e.printStackTrace();
    }
    okHttpClient.setCache( sCache );
    okHttpClient.setReadTimeout( 3600, TimeUnit.SECONDS );
    okHttpClient.setConnectTimeout( 3600, TimeUnit.SECONDS );
    sClient = new OkClient( okHttpClient );
}
项目:LetsDoThis-Android    文件:NetworkHelper.java   
public static RestAdapter.Builder getRequestAdapterBuilder()
{

    RequestInterceptor requestInterceptor = new RequestInterceptor()
    {
        @Override
        public void intercept(RequestFacade request)
        {
            Context context = LDTApplication.getContext();
            String northstarApiKey = context.getString(R.string.northstar_api_key);
            request.addHeader("X-DS-REST-API-Key", northstarApiKey);
        }
    };

    return new RestAdapter.Builder().setLogLevel(RestAdapter.LogLevel.FULL)
            .setErrorHandler(new RetrofitErrorHandler())
            .setClient(new OkClient(makeTimeoutClient(READ_TIMEOUT, CONNECT_TIMEOUT)))
            .setRequestInterceptor(requestInterceptor).setLogLevel(RestAdapter.LogLevel.FULL)
            .setLog(new AndroidLog("LDTHttp"));
}
项目:android-mg-bootstrap    文件:MGRestClient.java   
/**
 * Return standard rest adapter configured for
 * the platform project.
 */
public RestAdapter getRestAdapter() {

    // Configured endpoint.
    String endpoint = getConfig().getBaseAPIURL();

    RestAdapter.Builder builder = new RestAdapter.Builder()
        .setClient(new OkClient(getOkHttpClient())).setEndpoint(endpoint);

    builder = builder.setConverter(new GsonConverter(gson)).setRequestInterceptor(new RequestInterceptor() {
        @Override
        public void intercept(RequestFacade request) {
            if (getConfig().getInterceptor() != null) {
                getConfig().getInterceptor().intercept(request);
            }
        }
    });

    if (getConfig().getLogging() != null) {

        // Emit complete log level with a REST tag.
        builder = builder.setLogLevel(RestAdapter.LogLevel.FULL).setLog(getConfig().getLogging());
    }

    return builder.build();
}
项目:RSSTS    文件:SlackClient.java   
public static void initialize() {

        RestAdapter.Log restLogs = new RestAdapter.Log() {
            @Override
            public void log(String s) {
                LogUtils.D("CLIENT", s);
            }
        };

        // create client
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.setReadTimeout(1, TimeUnit.MINUTES);
        okHttpClient.setWriteTimeout(1, TimeUnit.MINUTES);
        okHttpClient.setConnectTimeout(1, TimeUnit.MINUTES);

        //slack
        RestAdapter slackRestAdapter = new RestAdapter.Builder()
                .setEndpoint(BASE_API)
                .setLog(restLogs)
                .setClient(new OkClient(okHttpClient))
                .setLogLevel(RestAdapter.LogLevel.FULL)
                .build();

        sSlack = slackRestAdapter.create(Slack.class);

    }
项目:poeditor-java    文件:POEditorClient.java   
private RestAdapter getAdapter() {
    RequestInterceptor requestInterceptor = new RequestInterceptor() {
        @Override
        public void intercept(RequestFacade requestFacade) {
            requestFacade.addHeader("Accept", "application/json");
        }
    };

    return new RestAdapter.Builder()
            //.setLogLevel(BuildConfig.DEBUG ? RestAdapter.LogLevel.FULL : RestAdapter.LogLevel.NONE)
            //.setLogLevel(RestAdapter.LogLevel.FULL)
            .setLogLevel(logLevel)
            .setRequestInterceptor(requestInterceptor)
            .setClient(new OkClient())
            .setEndpoint(this.endpoint).build();
}
项目:github-repoview    文件:RestServiceGenerator.java   
public static <S> S createService(Class<S> serviceClass, String baseUrl, final String basicAuthorization) {
    RestAdapter.Builder restBuilder = new RestAdapter.Builder()
            .setEndpoint(baseUrl)
            .setClient(new OkClient(new OkHttpClient()))
            .setConverter(new GsonConverter(Utils.getDefaultGsonInstance()))
            .setLogLevel(RestAdapter.LogLevel.BASIC);
    if(basicAuthorization != null) {
        restBuilder.setRequestInterceptor(new RequestInterceptor() {
            @Override
            public void intercept(RequestFacade request) {
                String authorization = "Basic " + basicAuthorization;
                request.addHeader("Authorization", authorization);
                request.addHeader("Accept", "application/json");
            }
        });
    }
    RestAdapter adapter = restBuilder.build();
    return adapter.create(serviceClass);
}
项目:yandex-disk-restapi-java    文件:RestClient.java   
public RestClient(final Credentials credentials, final OkHttpClient client, final String serverUrl) {
    this.credentials = credentials;
    this.client = client;
    try {
        this.serverURL = new URL(serverUrl).toExternalForm();
    } catch (MalformedURLException ex) {
        throw new RuntimeException(ex);
    }

    this.builder = new RestAdapter.Builder()
            .setClient(new OkClient(client))
            .setEndpoint(getUrl())
            .setRequestInterceptor(new RequestInterceptorImpl(credentials.getHeaders()))
            .setErrorHandler(new ErrorHandlerImpl())
            .setLogLevel(LOG_LEVEL);

    this.cloudApi = builder
            .build()
            .create(CloudApi.class);
}
项目:fiware-android-sdk    文件:ServiceGenerator.java   
public static <S> S createService(Class<S> serviceClass, String endpoint, final String token) {
    // set endpoint url and use OkHTTP as HTTP client
    RestAdapter.Builder builder = new RestAdapter.Builder()
            .setEndpoint(endpoint)
            .setConverter(new JacksonConverter())
            .setLogLevel(BuildConfig.DEBUG ? RestAdapter.LogLevel.FULL : RestAdapter.LogLevel.BASIC)
            .setClient(new OkClient(new OkHttpClient()));


    builder.setRequestInterceptor(new RequestInterceptor() {
        @Override
        public void intercept(RequestFacade request) {
            request.addHeader(Constants.HEADER_ACCEPT, "application/json");
            if (token != null) {
                request.addHeader(Constants.HEADER_TOKEN, token);
            }
        }
    });
    RestAdapter adapter = builder.build();
    return adapter.create(serviceClass);
}
项目:marsTemp    文件:Api.java   
/**
 * Init the http-client and cache.
 */
private static void initClient(Context cxt) {
    // Create an HTTP client that uses a cache on the file system. Android applications should use
    // their Context to get a cache directory.
    OkHttpClient okHttpClient = new OkHttpClient();
    //      okHttpClient.networkInterceptors().add(new StethoInterceptor());

    File cacheDir = new File(cxt != null ? cxt.getCacheDir().getAbsolutePath() : System.getProperty(
            "java.io.tmpdir"), UUID.randomUUID().toString());
    try {
        sCache = new com.squareup.okhttp.Cache(cacheDir, sCacheSize);
    } catch (IOException e) {
        e.printStackTrace();
    }
    okHttpClient.setCache(sCache);
    okHttpClient.setReadTimeout(3600, TimeUnit.SECONDS);
    okHttpClient.setConnectTimeout(3600, TimeUnit.SECONDS);
    sClient = new OkClient(okHttpClient);



    RestAdapter adapter = new RestAdapter.Builder().setClient(sClient).setRequestInterceptor(sInterceptor)
            .setLogLevel(RestAdapter.LogLevel.FULL).setEndpoint(sHost).build();
    s = adapter.create(S.class);
}
项目:BetaSeries    文件:BetaSeriesModule.java   
@Singleton
@Provides
public BetaSeriesAPI provideBetaSeriesApi(OkHttpClient okHttpClient, AuthenticationManager authenticationManager) {
    return new RestAdapter.Builder()
            .setEndpoint(BuildConfig.URL_BETASERIES)
            .setLogLevel(RestAdapter.LogLevel.FULL)
            .setClient(new OkClient(okHttpClient))
            .setLog(new AndroidLog("Retrofit"))
            .setRequestInterceptor(request -> {
                request.addHeader("X-BetaSeries-Key", BuildConfig.API_KEY);
                request.addHeader("X-BetaSeries-Version", "2.4");
                request.addHeader("Accept", "application/json");

                String userToken = authenticationManager.getToken();
                if (userToken != null)
                    request.addHeader("X-BetaSeries-Token", userToken);
            })
            .build()
            .create(BetaSeriesAPI.class);
}
项目:jjug-2015-reactive-streams    文件:ReactiveStreamsWithRxJavaTest.java   
private Publisher<DoorkeeperEvent> fromOtherPublisher() {
    /**
     * DoorkeeperのAPIを利用する
     */
    RestAdapter retrofit = new RestAdapter.Builder()
            .setEndpoint("http://api.doorkeeper.jp/")
            .setClient(new OkClient(new OkHttpClient()))
            .setRequestInterceptor(request -> request.addHeader("content-type", "application/json"))
            .build();
    Doorkeeper doorkeeper = retrofit.create(Doorkeeper.class);
    /**
     * 今回のイベントを探す。
     */
    Observable<DoorkeeperEvent> events = doorkeeper.findEventById(26547L);
    return RxReactiveStreams.toPublisher(events);
}
项目:android-tmdb    文件:MovieDbApi.java   
private MovieService getMovieService() {

        if (sService == null ) {
            Gson gson = new GsonBuilder().create();

            RestAdapter.Builder builder = new RestAdapter.Builder()
                  .setEndpoint(ENDPOINT)
                  .setConverter(new GsonConverter(gson))
                  .setClient(new OkClient())
                  .setLogLevel(RestAdapter.LogLevel.BASIC);
                  //.setLogLevel(RestAdapter.LogLevel.FULL);

            sService = builder.build().create(MovieService.class);
        }

        return sService;
    }
项目:Knight    文件:AppModule.java   
@Provides
@AppScope
IApi providesApi(final NetUtils netUtils, OkClient client) {
    RestAdapter restAdapter = new RestAdapter.Builder()
            .setEndpoint(IApi.API_ENDPOINT)
            .setClient(client)
            .setLogLevel(RestAdapter.LogLevel.BASIC)
            .setRequestInterceptor(new RequestInterceptor() {
                @Override
                public void intercept(RequestFacade request) {
                    request.addHeader("Content-type", "application/json");
                    if (netUtils.isNetworkAvailable()) {
                        int maxAge = 60; // read from cache for 1 minute
                        request.addHeader("Cache-Control", "public, max-age=" + maxAge);
                    } else {
                        int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
                        request.addHeader("Cache-Control", "public, only-if-cached, max-stale=" + maxStale);
                    }
                }
            })
            .build();

    return restAdapter.create(IApi.class);
}
项目:wyre-old    文件:ServiceGenerator.java   
public static <S> S createService(Class<S> serviceClass, String baseUrl,
                                  final AccessTokenResult accessToken) {
    // Create builder for rest adapter with baseUrl and client
    RestAdapter.Builder builder = new RestAdapter.Builder()
            .setEndpoint(baseUrl)
            .setClient(new OkClient(new OkHttpClient()));

    // Check if username and password were passed
    if (accessToken != null) {
        builder.setRequestInterceptor(new RequestInterceptor() {
            @Override
            public void intercept(RequestFacade request) {
                request.addHeader("Accept", "application/json");
                request.addHeader("Authorization",
                        accessToken.getScope() + " " + accessToken.getAccessToken());
            }
        });
    }

    // Create adapter from builder
    RestAdapter adapter = builder.build();

    // Create new adapter with the passed class as the interface.
    return adapter.create(serviceClass);
}
项目:GitHub    文件:ApiServiceModule.java   
@Provides
@Singleton
RestAdapter provideRestAdapter(Application application, OkHttpClient okHttpClient) {
    RestAdapter.Builder builder = new RestAdapter.Builder();
    builder.setClient(new OkClient(okHttpClient))
            .setEndpoint(ENDPOINT);
    return builder.build();
}
项目:Hello-Music-droid    文件:RestServiceFactory.java   
public static <T> T createStatic(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() {
        PreferencesUtility prefs = PreferencesUtility.getInstance(context);

        @Override
        public void intercept(RequestFacade request) {
            //7-days cache
            request.addHeader("Cache-Control", String.format("max-age=%d,%smax-stale=%d", Integer.valueOf(60 * 60 * 24 * 7), prefs.loadArtistImages() ? "" : "only-if-cached,", 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);

}
项目:xlight_android_native    文件:ApiFactory.java   
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)));
}
项目:Build-it-Bigger    文件:RetrofitTest.java   
@Test
public void testGetJokes() throws IOException {

    //Building the RestAdapter again because UrlFetchClient needs appengine module
    // and doesn't work during testing. Also, OkClient is not supported by GCE
    RestAdapter restAdapter = new RestAdapter.Builder()
            .setEndpoint(ServiceGenerator.API_ENDPOINT_URL)
            .setClient(new OkClient(new OkHttpClient()))
            .build();
    ApiInterface apiInterface = restAdapter.create(ApiInterface.class);
    assertEquals("Incorrect response : ", 5, apiInterface.getRandomJokesSync(5).getJokeList().size());
}
项目:Mono2Clean-V3    文件:ApiProvider.java   
public static RestAdapter getApi(){
    OkHttpClient client = new OkHttpClient();

    return new RestAdapter.Builder()
            .setLogLevel(RestAdapter.LogLevel.FULL)
            .setClient(new OkClient(client))
            .setEndpoint(ENDPOINT)
            .build();
}
项目:xowa_android    文件:RbPageEndpointsCache.java   
private RbPageService.RbPageEndpoints createRbService(final Site site) {
    RbPageService.RbPageEndpoints webService;
    final String domain = site.getApiDomain();
    final WikipediaApp app = WikipediaApp.getInstance();
    RestAdapter restAdapter = new RestAdapter.Builder()
            .setLogLevel(Prefs.getRetrofitLogLevel())

            .setClient(new OkClient(OkHttpConnectionFactory.createClient(app)))

            .setRequestInterceptor(new RequestInterceptor() {
                @Override
                public void intercept(RequestFacade request) {
                    app.getMccMncStateHandler().injectMccMncHeader(app, domain, request);
                    app.injectCustomHeaders(request, site);
                }
            })

            .setEndpoint(String.format(Locale.ROOT, Prefs.getRestbaseUriFormat(),
                    WikipediaApp.getInstance().getNetworkProtocol(), domain))

                    // following is only needed for the hacky PageLead.Protection deserialization
                    // remove once our service handles this better (see T111131)
            .setConverter(new GsonConverter(new GsonBuilder()
                    .registerTypeAdapter(RbPageLead.Protection.class,
                            new RbPageLead.Protection.Deserializer())
                    .create()))

            .build();
    webService = restAdapter.create(RbPageService.RbPageEndpoints.class);
    return webService;
}
项目:xowa_android    文件:MwPageEndpointsCache.java   
private MwPageService.MwPageEndpoints createMwService(final Site site) {
    MwPageService.MwPageEndpoints webService;
    final String domain = site.getApiDomain();
    final WikipediaApp app = WikipediaApp.getInstance();
    RestAdapter restAdapter = new RestAdapter.Builder()
            .setLogLevel(Prefs.getRetrofitLogLevel())

            .setClient(new OkClient(OkHttpConnectionFactory.createClient(app)))

            .setRequestInterceptor(new RequestInterceptor() {
                @Override
                public void intercept(RequestFacade request) {
                    app.getMccMncStateHandler().injectMccMncHeader(app, domain, request);
                    app.injectCustomHeaders(request, site);
                }
            })

            .setEndpoint(WikipediaApp.getInstance().getNetworkProtocol() + "://" + domain)

                    // following is only needed for the hacky PageLead.Protection deserialization
                    // remove once https://phabricator.wikimedia.org/T69054 is resolved
            .setConverter(new GsonConverter(new GsonBuilder()
                    .registerTypeAdapter(MwPageLead.Protection.class,
                            new MwPageLead.Protection.Deserializer())
                    .create()))

            .build();
    webService = restAdapter.create(MwPageService.MwPageEndpoints.class);
    return webService;
}
项目:fiat    文件:RetrofitConfig.java   
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
OkClient okClient() {
  val client = okHttpClientConfig.create();
  client.setConnectionPool(new ConnectionPool(maxIdleConnections, keepAliveDurationMs));
  client.setRetryOnConnectionFailure(retryOnConnectionFailure);
  client.interceptors().add(new RetryingInterceptor(maxElapsedBackoffMs));
  return new OkClient(client);
}