public static ApiService buildApiService() { HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient clientOkHttp = new OkHttpClient.Builder() .addInterceptor(interceptor) .build(); Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://jsonplaceholder.typicode.com") .client(clientOkHttp) .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().create())) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build(); return retrofit.create(ApiService.class); }
private Api() { HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor(); logInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); File cacheFile = new File(App.getAppContext().getCacheDir(), "cache"); Cache cache = new Cache(cacheFile, 1024 * 1024 * 100); //100Mb OkHttpClient okHttpClient = new OkHttpClient.Builder() .readTimeout(7676, TimeUnit.MILLISECONDS) .connectTimeout(7676, TimeUnit.MILLISECONDS) .addInterceptor(headInterceptor) .addInterceptor(logInterceptor) .addNetworkInterceptor(new HttpCacheInterceptor()) .cache(cache) .build(); Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").serializeNulls().create(); retrofit = new Retrofit.Builder() .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create(gson)) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .baseUrl(C.BASE_URL) .build(); service = retrofit.create(ApiService.class); }
private static Retrofit create() { OkHttpClient.Builder builder = new OkHttpClient().newBuilder(); builder.readTimeout(10, TimeUnit.SECONDS); builder.connectTimeout(9, TimeUnit.SECONDS); builder.addNetworkInterceptor(new StethoInterceptor()); if (BuildConfig.DEBUG) { HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); builder.addInterceptor(interceptor); } return new Retrofit.Builder().baseUrl(ENDPOINT) .client(builder.build()) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build(); }
private static Retrofit build(){ if(null == retrofitInstance){ synchronized (Retrofit.class){ if(null == retrofitInstance){ // 双重检验锁,仅第一次调用时实例化 retrofitInstance = new Retrofit.Builder() // baseUrl总是以/结束,@URL不要以/开头 .baseUrl(BuildConfig.API_SERVER_URL) // 使用OkHttp Client .client(buildOkHttpClient()) // 集成RxJava处理 .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // 集成Gson转换器 .addConverterFactory(buildGsonConverterFactory()) .build(); } } } return retrofitInstance; }
private RetrofitClient(){ OkHttpClient.Builder builder = new OkHttpClient.Builder(); builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS) .sslSocketFactory(createSSLSocketFactory(),new TrustAllManager())//信任所有 .addInterceptor(new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() { @Override public void log(String message) { Log.i("okhttp32",message); } }).setLevel(HttpLoggingInterceptor.Level.BODY)) ; mOkHttpClient = builder.build(); mRetrofit = new Retrofit.Builder() .client(mOkHttpClient) .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create(buildGson())) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build(); }
@Before public void beforeEachTest() { server = new MockWebServer(); NumbersWebService numberAPI = new Retrofit.Builder() .baseUrl(server.url("/").toString()) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build() .create(NumbersWebService.class); infrastructure = new TriviaInfrastructure( numberAPI, new TriviaGenerator(), new PayloadMapper(), new PayloadValidator(), Schedulers.trampoline() // non-concurrent integration on tests ); }
/** * @param builder * @param client * @param httpUrl * @return * @author: jess * @date 8/30/16 1:15 PM * @description:提供retrofit */ @Singleton @Provides Retrofit provideRetrofit(Application application, @Nullable RetrofitConfiguration configuration, Retrofit.Builder builder, OkHttpClient client , HttpUrl httpUrl, Gson gson) { builder .baseUrl(httpUrl)//域名 .client(client);//设置okhttp if (configuration != null) configuration.configRetrofit(application, builder); builder .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//使用rxjava .addConverterFactory(GsonConverterFactory.create(gson));//使用Gson return builder.build(); }
@Override public Single<RetrofitWrapper> provideAuthRetrofit() { return Single.fromCallable(() -> { OkHttpClient.Builder builder = new OkHttpClient.Builder() .readTimeout(30, TimeUnit.SECONDS) .addInterceptor(HttpLogger.DEFAULT_LOGGING_INTERCEPTOR); ProxyUtil.applyProxyConfig(builder, proxySettings.getActiveProxy()); Gson gson = new GsonBuilder().create(); final Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://oauth.vk.com/") .addConverterFactory(GsonConverterFactory.create(gson)) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .client(builder.build()) .build(); return RetrofitWrapper.wrap(retrofit, false); }); }
@Singleton @Provides Retrofit provideRetrofit(@Nullable RetrofitConfiguration configuration, Retrofit.Builder builder, OkHttpClient client, HttpUrl httpUrl) { builder //domain name .baseUrl(httpUrl) //Set okhttp .client(client) //TODO: to use use LiveData //.addCallAdapterFactory(new LiveDataCallAdapterFactory()) //use rxjava .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) //use Gson .addConverterFactory(GsonConverterFactory.create()); if (configuration != null) configuration.configRetrofit(mApplication, builder); return builder.build(); }
/** * 实际由getInstance() 进行调用创建 */ private RetrofitUtils() { // 创建 OKHttpClient OkHttpClient.Builder builder = new OkHttpClient.Builder(); builder.connectTimeout(this.DEFAULT_TIME_OUT, TimeUnit.SECONDS)//设置全局请求的连接超时时间,默认为15s .writeTimeout(this.DEFAULT_READ_TIME_OUT, TimeUnit.SECONDS)//写操作 超时时间 .readTimeout(this.DEFAULT_READ_TIME_OUT, TimeUnit.SECONDS);//设置全局请求的数据读取超时时间,默认为30s // 向okhttp中添加公共参数拦截器 builder.addInterceptor(mBaseInterceptor != null ? mBaseInterceptor : BaseInterceptor.getDefault()); //创建okhttp实例 OkHttpClient client = builder.build(); //配置你的Gson,在不同环境下gson对Data的转化可能不一样,这里使用统一的格式 Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd hh:mm:ss").create(); // 创建Retrofit,将gson和okhttp加入进来 mRetrofit = new Retrofit.Builder().baseUrl(this.BASE_URL)//设置基础域名。网络请求由此拼接(注意:需要/结尾,且此处与单独有相同路径时会智能纠错:www/api/+api/xxx会纠错为www/api/xxx) .addConverterFactory(GsonConverterFactory.create(gson))//设置json返回消息的解析库(这里使用gson) .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//此在与RxJava联用时才使用 .client(client)//配置okhttp配置。可无(为空时,retrofit会使用默认配置) .build(); }
private void init() { HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor() .setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient client = new OkHttpClient() .newBuilder() .addInterceptor(interceptor) .build(); service = new Retrofit.Builder() .baseUrl("https://api.github.com/") .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .client(client) .build() .create(GitHubService.class); }
@Override public void onRefresh() { String baseUrl = "http://gank.io/api/"; Retrofit retrofit = new Retrofit.Builder() .baseUrl(baseUrl) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build(); ApiService apiService = retrofit.create(ApiService.class); apiService.getClassifyData("福利", 1) .map(new BaseResFunc<List<Gank>>()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(mObserver); }
private HttpManager() { OkHttpClient.Builder okHttpClientBuild = new OkHttpClient.Builder() .connectTimeout(30, TimeUnit.SECONDS); OkHttpClient okHttpClient = okHttpClientBuild.build(); mApi = new Retrofit.Builder() .baseUrl("http://image.baidu.com/") .client(okHttpClient) .addCallAdapterFactory(RxJava2WithProgressCallAdapterFactory.createAsync()) .addCallAdapterFactory(RxJava2CallAdapterFactory.createAsync()) .addConverterFactory(ScalarsConverterFactory.create()) .addConverterFactory(FileConverterFactory.create()) .build() .create(Api.class); }
private void initWithBaseUrl(String baseUrl){ HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(5000, TimeUnit.MILLISECONDS) .readTimeout(5000, TimeUnit.MILLISECONDS) .writeTimeout(5000, TimeUnit.MILLISECONDS) .addInterceptor(loggingInterceptor) .build(); retrofit = new Retrofit.Builder() .baseUrl(baseUrl) .addConverterFactory(GsonConverterFactory.create()) .client(client) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build(); }
private RemoteHelper(){ mOkHttpClient = new OkHttpClient.Builder() .addNetworkInterceptor( new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); //在这里获取到request后就可以做任何事情了 Response response = chain.proceed(request); Log.d(TAG, "intercept: "+request.url().toString()); return response; } } ).build(); mRetrofit = new Retrofit.Builder() .client(mOkHttpClient) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .baseUrl(Constant.API_BASE_URL) .build(); }
public static Retrofit getRetrofit(@NonNull String blogUrl, @NonNull OkHttpClient httpClient) { String baseUrl = NetworkUtils.makeAbsoluteUrl(blogUrl, "ghost/api/v0.1/"); Gson gson = new GsonBuilder() .registerTypeAdapter(Date.class, new DateDeserializer()) .registerTypeAdapter(ConfigurationList.class, new ConfigurationListDeserializer()) .registerTypeAdapterFactory(new PostTypeAdapterFactory()) .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .setExclusionStrategies(new RealmExclusionStrategy(), new AnnotationExclusionStrategy()) .create(); return new Retrofit.Builder() .baseUrl(baseUrl) .client(httpClient) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // for HTML output (e.g., to get the client secret) .addConverterFactory(StringConverterFactory.create()) // for raw JSONObject output (e.g., for the /configuration/about call) .addConverterFactory(JSONObjectConverterFactory.create()) // for domain objects .addConverterFactory(GsonConverterFactory.create(gson)) .build(); }
public Single<String> getAuthenticationTokenFromYelp(@NonNull String clientID, @NonNull String clientSecret) { if (retrofit == null) { retrofit = new Retrofit.Builder() .baseUrl("https://api.yelp.com/") .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build(); } return retrofit.create(YelpAuthenticationService.class).getAutenticationTokenFromYelp(OAUTH_GRANT, clientID, clientSecret) .subscribeOn(Schedulers.io()) .map(new Function<YelpAuthentication, String>() { @Override public String apply(@io.reactivex.annotations.NonNull YelpAuthentication yelpAuthentication) throws Exception { if (yelpAuthentication != null) { return yelpAuthentication.getAccess_token(); } throw new Exception("Error :"); } }); }
private ApiManager() { cookieJar = new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(Utils.getApp())); OkHttpClient.Builder builder = new OkHttpClient().newBuilder(); builder.readTimeout(30, TimeUnit.SECONDS); builder.connectTimeout(29, TimeUnit.SECONDS); builder.cookieJar(cookieJar); builder.addInterceptor(new RequestInterceptor()); builder.addNetworkInterceptor(new NetworkInterceptor()); OkHttpClient okHttpClient = builder.build(); Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://" + domain) .client(okHttpClient) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build(); apiService = retrofit.create(ApiService.class); }
public static void setBaseUrl(String url) { BASE_URL = url; retrofitGson = new Retrofit.Builder() .baseUrl(BASE_URL) .client(client) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build(); }
private RetrofitHelper() { // 初始化Retrofit Retrofit retrofit = new Retrofit.Builder() .baseUrl(Constant.SERVER_URL) .addConverterFactory(GsonConverterFactory.create()) // json解析 .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // 支持RxJava .build(); retrofitService = retrofit.create(RetrofitService.class); }
/** * Rx方式使用 */ private void rxRequest() { Retrofit retrofit = new Retrofit.Builder() .baseUrl(Constant.SERVER_URL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // 支持RxJava .client(RetrofitUtils.getOkHttpClient()) // 打印请求参数 .build(); RetrofitService service = retrofit.create(RetrofitService.class); Observable<PostInfo> observable = service.getPostInfoRx("yuantong", "11111111111"); observable.subscribeOn(Schedulers.io()) // 在子线程中进行Http访问 .observeOn(AndroidSchedulers.mainThread()) // UI线程处理返回接口 .subscribe(new Observer<PostInfo>() { // 订阅 @Override public void onSubscribe(@NonNull Disposable d) { } @Override public void onNext(@NonNull PostInfo postInfo) { Log.i("http返回:", postInfo.toString()); Toast.makeText(MainActivity.this, postInfo.toString(), Toast.LENGTH_SHORT).show(); } @Override public void onError(@NonNull Throwable e) { } @Override public void onComplete() { } }); }
private HttpChannel() { // 初始化Retrofit Retrofit retrofit = new Retrofit.Builder() .baseUrl(Constant.SERVER_URL) .addConverterFactory(GsonConverterFactory.create()) // json解析 .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // 支持RxJava .client(RetrofitUtils.getOkHttpClient()) // 打印请求参数 .build(); retrofitService = retrofit.create(RetrofitService.class); }
@Before public void setUp() throws Exception { Retrofit retrofit = new Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .baseUrl("https://api.shodan.io/") .build(); MockRetrofit mockRetrofit = new MockRetrofit.Builder(retrofit) .networkBehavior(networkBehavior).build(); BehaviorDelegate<ApiService> delegate = mockRetrofit.create(ApiService.class); apiRestMock = new ApiRestMock(delegate); }
@Provides @Singleton Retrofit providesRetrofit(ObjectMapper objectMapper, OkHttpClient okHttpClient) { return new Retrofit.Builder() .baseUrl(org.codenergic.theskeleton.data.BuildConfig.BASE) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(JacksonConverterFactory.create(objectMapper)) .client(okHttpClient) .build(); }
private HttpMethod() { retrofit = new Retrofit.Builder() .client(genericClient()) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .baseUrl(BASE_URL) .build(); }
@Test public void provideYahooRetrofit() { Retrofit retrofit = module.provideYahooRetrofit(AppModule.provideGson()); assertThat(retrofit.baseUrl().toString(), is("https://query.yahooapis.com/")); assertThat(retrofit.callAdapterFactories(), hasItem(isA(RxJava2CallAdapterFactory.class))); assertThat(retrofit.converterFactories(), hasItem(isA(GsonConverterFactory.class))); }
@Singleton @Provides Retrofit retrofit(OkHttpClient okHttpClient) { return new Retrofit .Builder() .baseUrl(BuildConfig.TMDB_BASE_URL) .addConverterFactory(GsonConverterFactory.create()) // serialization and deserialization of objects .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // ?? .client(okHttpClient) .build(); }
public static Retrofit getClient() { if (retrofit == null) { retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build(); } return retrofit; }
private MRetrofit(Context context, Map<String, String> headers) { HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(); httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC); OkHttpClient okHttpClient = new OkHttpClient.Builder() .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS) .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS) // .sslSocketFactory(SSLHelper.getSSLCertifcation(context))//为OkHttp对象设置SocketFactory用于双向认证 .addInterceptor(new BaseInterceptor(headers)) .addInterceptor(new AddCookiesInterceptor(context)) .addInterceptor(new SaveCookiesInterceptor(context)) .addInterceptor(httpLoggingInterceptor) .addNetworkInterceptor(new CaheInterceptor()) .cache(new Cache(new File(ContextHolder.getContext().getCacheDir(),"mReCache"),1024*1024*10)) .build(); Retrofit retrofit = new Retrofit.Builder() .client(okHttpClient) .baseUrl(IP) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//1.X为RxJavaCallAdapterFactory .build(); retrofitService = retrofit.create(RetrofitService.class); }
public NYTimesDataLoader() { Retrofit retrofit = new Retrofit.Builder() .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(JacksonConverterFactory.create()) .baseUrl("http://api.nytimes.com/") .build(); nyTimesService = retrofit.create(NYTimesService.class); }
@Provides @Replaceable public static RetrofitWeatherApi weatherAPI(@Named("endpointUrl") String url) { return new Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .baseUrl(url) .client(new OkHttpClient.Builder() .connectTimeout(5, TimeUnit.SECONDS) .readTimeout(5, TimeUnit.SECONDS) .build()) .build() .create(RetrofitWeatherApi.class); }
private Retrofit provideRetrofit(OkHttpClient okHttpClient) { Gson gson = new GsonBuilder() .registerTypeAdapterFactory(new Adapter()) .create(); return new Retrofit.Builder() .baseUrl("https://api.soundcloud.com/") .addConverterFactory(GsonConverterFactory.create(gson)) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .client(okHttpClient) .build(); }
private <T> T createRestServices(OkHttpClient okHttpClient, String baseUrl, Class<T> servicesClass) { final Gson gson = new GsonBuilder().create(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(baseUrl) .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create(gson)) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build(); return retrofit.create(servicesClass); }
public static Retrofit getClient(String baseUrl) { if (retrofit==null) { retrofit = new Retrofit.Builder() .baseUrl(baseUrl) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build(); } return retrofit; }
private void buildApiClient(String baseUrl) { apiClient = new Retrofit.Builder() .baseUrl(baseUrl) .client(httpClient) .addConverterFactory(GsonConverterFactory.create(gson)) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build() .create(ApiClient.class); }
@WeiXinURL @Provides @FragmentScope Retrofit provideWeiXinRetrofit(Retrofit.Builder builder, OkHttpClient client) { return builder .baseUrl(WeiXinApi.HOST) .client(client) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build(); }
@Provides @Reusable static NumbersWebService webService(OkHttpClient customHttpClient) { Retrofit adapter = new Retrofit.Builder() .baseUrl(NumbersWebService.BASE_URL) .client(customHttpClient) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build(); return adapter.create(NumbersWebService.class); }
/** * @param gson Gson instance for parsing JSON response bodies * @return a Retrofit instance for Yahoo's public API */ @Provides @Named("yahooRetrofit") @Singleton Retrofit provideYahooRetrofit(Gson gson) { return new Retrofit.Builder() .baseUrl("https://query.yahooapis.com/") .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create(gson)) .build(); }