public static Retrofit retrofit() { if (mRetrofit == null) { OkHttpClient.Builder builder = new OkHttpClient.Builder(); if (BuildConfig.DEBUG) { // Log信息拦截器 HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); //设置 Debug Log 模式 builder.addInterceptor(loggingInterceptor); } OkHttpClient okHttpClient = builder.build(); mRetrofit = new Retrofit.Builder() .baseUrl(ApiStores2.URL_BASE) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .client(okHttpClient) .build(); } return mRetrofit; }
private NetWorkManager() { this.mOkHttpClient = RetrofitUrlManager.getInstance().with(new OkHttpClient.Builder()) //RetrofitUrlManager 初始化 .readTimeout(5, TimeUnit.SECONDS) .connectTimeout(5, TimeUnit.SECONDS) .build(); this.mRetrofit = new Retrofit.Builder() .baseUrl(APP_DEFAULT_DOMAIN) .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//使用rxjava .addConverterFactory(GsonConverterFactory.create())//使用Gson .client(mOkHttpClient) .build(); this.mOneApiService = mRetrofit.create(OneApiService.class); this.mTwoApiService = mRetrofit.create(TwoApiService.class); this.mThreeApiService = mRetrofit.create(ThreeApiService.class); }
public static ChatDemoApi apiManager(){ if(chatDemoApi == null){ HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient okHttpClient = new OkHttpClient.Builder() .addInterceptor(logging) .connectTimeout(10, TimeUnit.SECONDS) .readTimeout(10, TimeUnit.SECONDS) .build(); Retrofit client = new Retrofit.Builder() .baseUrl(EndPointConstant.BASE_URL) .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create()) .build(); chatDemoApi = client.create(ChatDemoApi.class); } return chatDemoApi; }
public static RetrofitInterface getRetrofit(String token) { OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); httpClient.addInterceptor(chain -> { Request original = chain.request(); Request.Builder builder = original.newBuilder() .addHeader("x-access-token", token) .method(original.method(),original.body()); return chain.proceed(builder.build()); }); RxJavaCallAdapterFactory rxAdapter = RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io()); return new Retrofit.Builder() .baseUrl(Constants.BASE_URL) .client(httpClient.build()) .addCallAdapterFactory(rxAdapter) .addConverterFactory(GsonConverterFactory.create()) .build().create(RetrofitInterface.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(RxJavaCallAdapterFactory.create()) .baseUrl(C.BASE_URL) .build(); service = retrofit.create(ApiService.class); }
/** * 创建ApiService实例 * * @param service Service类型 * @param <T> * @return */ private static <T> T creatService(final Class<T> service) { HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(AppData.LOG_DEBUG ? HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.NONE); OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(CONNECT_TIME_OUT_SECONDS, TimeUnit.SECONDS) .readTimeout(READ_TIME_OUT_SECONDS, TimeUnit.SECONDS) .addInterceptor(new LoggingInterceptor()) .addInterceptor(new ParamsInterceptord()) .build(); return new Retrofit.Builder() .baseUrl(AppData.BaseUrl) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .client(client) .build() .create(service); }
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 void onCustomApiCall(View view) { final String name = "18688994275"; final String pass = "123456"; final CustomRequest request = EasyHttp.custom() .addConverterFactory(GsonConverterFactory.create(new Gson())) .sign(true) .timeStamp(true) .params(ComParamContact.Login.ACCOUNT, name) .params(ComParamContact.Login.PASSWORD, MD5.encrypt4login(pass, AppConstant.APP_SECRET)) .build(); LoginService mLoginService = request.create(LoginService.class); Observable<AuthModel> observable = request.apiCall(mLoginService.login("v1/account/login", request.getParams().urlParamsMap)); Disposable disposable = observable.subscribe(new Consumer<AuthModel>() { @Override public void accept(@NonNull AuthModel authModel) throws Exception { showToast(authModel.toString()); } }, new Consumer<Throwable>() { @Override public void accept(@NonNull Throwable throwable) throws Exception { showToast(throwable.getMessage()); } }); //EasyHttp.cancelSubscription(disposable);//取消订阅 }
default ProtoCore getProtocore() { Gson gson = NetworkUtilities.getGson(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(getSatispayContext().getBaseUrl()) .addConverterFactory(GsonConverterFactory.create(gson)) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .client( getProtocoreHttpClientProvider().getProtocoreClient( getSatispayContext(), getSecurePersistenceManager(), getSessionManager(), getSdkDeviceInfo() ) ) .build(); return retrofit.create(ProtoCore.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(); }
@Provides Retrofit retrofit() { OkHttpClient client = new OkHttpClient.Builder() .addInterceptor(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { return chain.proceed( chain.request() .newBuilder() .addHeader("Authorization", "Client-ID " + ImgurService.CLIENT_ID) .build()); } }) .build(); return new Retrofit.Builder() .client(client) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .baseUrl("https://api.imgur.com/3/") .build(); }
public static void main(String... args) throws IOException, InterruptedException { MockWebServer server = new MockWebServer(); server.start(); server.enqueue(new MockResponse()); Retrofit retrofit = new Retrofit.Builder() .baseUrl(server.url("/")) .addConverterFactory(new JsonStringConverterFactory(GsonConverterFactory.create())) .build(); Service service = retrofit.create(Service.class); Call<ResponseBody> call = service.example(new Filter("123")); Response<ResponseBody> response = call.execute(); // TODO handle user response... // Print the request path that the server saw to show the JSON query param: RecordedRequest recordedRequest = server.takeRequest(); System.out.println(recordedRequest.getPath()); server.shutdown(); }
private ApiClient() { HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient client = new OkHttpClient.Builder() .addInterceptor(interceptor) .addInterceptor(new SessionInterceptor()) //.addInterceptor(new GzipRequsetInterceptor()) .build(); OKHttpUtils.cancelCallWithTag(client); this.retrofit = new Retrofit.Builder() .baseUrl(API_HOST) .client(client) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.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 ); }
@Before public void setUp() throws IOException { mMockServer = new MockWebServer(); mMockServer.start(); Retrofit retrofit = (new Retrofit.Builder().baseUrl(mMockServer.url("").toString()) .addConverterFactory(ScalarsConverterFactory.create()) .addConverterFactory(GsonConverterFactory.create())).build(); CivifyLoginService civifyLoginService = retrofit.create(CivifyLoginService.class); CivifyMeService civifyMeService = retrofit.create(CivifyMeService.class); SharedPreferences.Editor editor = mock(SharedPreferences.Editor.class); mSharedPreferences = mock(SharedPreferences.class); mLoginFinishedCallbackMock = mock(LoginFinishedCallback.class); when(mSharedPreferences.edit()).thenReturn(editor); mUser = new User("username", "name", "surname", "email", "password", "password"); mLoginAdapter = new LoginAdapterImpl(civifyLoginService, civifyMeService, mSharedPreferences); }
@Before public void setUp() { OkHttpClient.Builder builder = new OkHttpClient.Builder() .addInterceptor(youtubeInterceptor) .addInterceptor(provideHttpLoggingInterceptor()) .connectTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS) .readTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS) .writeTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS) .cache(cache); OkHttpClient httpClient = builder.build(); retrofit = new Retrofit.Builder() .baseUrl(APIYouTube.URL) .client(httpClient) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build(); mApi = retrofit.create(APIYouTube.class); }
private void requestRetrofit() { Retrofit retrofit = new Retrofit.Builder().baseUrl("http://www.baidu.com").addConverterFactory(GsonConverterFactory.create()).build(); RequestService requestService = retrofit.create(RequestService.class); final Call<RequestService.User> call = requestService.getUser("myname", "mypassword"); new Thread(new Runnable() { @Override public void run() { try { RequestService.User body = call.execute().body(); Log.i(TAG, "requestRetrofit: " + body.toString()); } catch (IOException e) { Log.i(TAG, "requestRetrofit: " + e.getMessage()); e.printStackTrace(); } } }).start(); }
public static RetrofitInterface getRetrofit(String email, String password) { String credentials = email + ":" + password; String basic = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP); OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); httpClient.addInterceptor(chain -> { Request original = chain.request(); Request.Builder builder = original.newBuilder() .addHeader("Authorization", basic) .method(original.method(),original.body()); return chain.proceed(builder.build()); }); RxJavaCallAdapterFactory rxAdapter = RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io()); return new Retrofit.Builder() .baseUrl(Constants.BASE_URL) .client(httpClient.build()) .addCallAdapterFactory(rxAdapter) .addConverterFactory(GsonConverterFactory.create()) .build().create(RetrofitInterface.class); }
@Before public void setUp() throws IOException, ParseException { setUpAward(); mMockWebServer = new MockWebServer(); mMockWebServer.start(); mGson = new GsonBuilder() .excludeFieldsWithoutExposeAnnotation() .setDateFormat(ServiceGenerator.RAILS_DATE_FORMAT) .create(); Retrofit retrofit = new Retrofit.Builder().baseUrl(mMockWebServer.url("").toString()) .addConverterFactory(GsonConverterFactory.create(mGson)).build(); AwardService awardService = retrofit.create(AwardService.class); SharedPreferences sharedPreferences = mock(SharedPreferences.class); mListAwardsSimpleCallbackMock = mock(ListAwardsSimpleCallback.class); mAwardSimpleCallbackMock = mock(AwardSimpleCallback.class); mAwardAdapter = new AwardAdapterImpl(awardService, sharedPreferences); mListExchangedAwardSimpleCallback = mock(ListExchangedAwardSimpleCallback.class); }
private static MastodonApi createMastodonApi(String domain, Context context) { SharedPreferences preferences = context.getSharedPreferences( context.getString(R.string.preferences_file_key), Context.MODE_PRIVATE); OkHttpClient okHttpClient = OkHttpUtils.getCompatibleClientBuilder(preferences) .addInterceptor(new AuthInterceptor(context)) .build(); Gson gson = new GsonBuilder() .registerTypeAdapter(Spanned.class, new SpannedTypeAdapter()) .create(); Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://" + domain) .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create(gson)) .build(); return retrofit.create(MastodonApi.class); }
@Provides @Singleton public Retrofit provideRetrofit(Application application, OkHttpClient okHttpClient, Retrofit.Builder builder, HttpUrl httpUrl, @Nullable RetrofitConfiguration configuration) { builder.baseUrl(httpUrl) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .client(okHttpClient); if (configuration != null) { configuration.configRetrofit(application, builder); } return builder.build(); }
public static ChuckNorrisApiService getApiService() { HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(); httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); okHttpClient = new OkHttpClient.Builder().addInterceptor(new BarricadeInterceptor()).addInterceptor(httpLoggingInterceptor).build(); Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.chucknorris.io").client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build(); return retrofit.create(ChuckNorrisApiService.class); }
private HttpMethod() { retrofit = new Retrofit.Builder() .client(genericClient()) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .baseUrl(BASE_URL) .build(); }
protected void rebuildRetrofitInstance(){ Retrofit.Builder builder = new Retrofit.Builder() .baseUrl(mURL.toString()) .client(createOkHttpClient()) .addConverterFactory(GsonConverterFactory.create()); mRetrofit = builder.build(); }
public static Retrofit getClient() { if (retrofit==null) { retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); } return retrofit; }
public static void init(Resources resources) { Retrofit retrofit = new Retrofit.Builder() .baseUrl(resources.getString(R.string.api_address)) .addConverterFactory(GsonConverterFactory.create()) .build(); service = retrofit.create(Service.class); }
@Singleton @Provides ApiService provideApiService() { Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create(); return new Retrofit.Builder() .baseUrl("http://192.168.0.103:8080") .addConverterFactory(GsonConverterFactory.create(gson)) .build() .create(ApiService.class); }
protected Retrofit createRetrofit(Retrofit.Builder builder, OkHttpClient client, String url) { return builder .baseUrl(url) .client(client) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build(); }
public static Retrofit getJokeRetrofit() { Retrofit retrofit = new Retrofit.Builder().baseUrl(Constants.Url.JOKE) .addConverterFactory(new NullOnEmptyConverterFactory()) .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().create())) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .client(OkHttpHelper.getOkClient()) .build(); return retrofit; }
public HttpService getService() { if (retrofit == null) { retrofit = new Retrofit.Builder() .baseUrl("https://kyfw.12306.cn/otn/") .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .client(getClient()) .build(); } return retrofit.create(HttpService.class); }
static <T> T getClient(Class<T> cls, String username, String psw, String url) { OkHttpClient.Builder builder = new OkHttpClient().newBuilder(); builder.readTimeout(10, TimeUnit.SECONDS); builder.connectTimeout(5, TimeUnit.SECONDS); if(BuildConfig.DEBUG){ builder.addInterceptor(new LoggingInterceptor()); } String credentials = username + ":" + psw; final String basic = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP); builder.addInterceptor(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request().newBuilder() .addHeader("Authorization", basic) .addHeader("Accept", "application/json") .build(); return chain.proceed(request); } }); OkHttpClient client = builder.build(); Gson gson = new GsonBuilder() .setDateFormat("yyyy-MM-dd HH:mm:ss") .create(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(url+API_URL) .client(client) .addConverterFactory(GsonConverterFactory.create(gson)) .build(); return retrofit.create(cls); }
public RetrofitServiceFactory(String endpoint, Duration timeout) { this.timeout = timeout; String correctedEndpoint = (endpoint.endsWith("/")) ? endpoint : endpoint + "/"; retrofitBuilder = new Retrofit.Builder() .baseUrl(correctedEndpoint) .addConverterFactory(GsonConverterFactory.create(getGson())); }
/** * 根据传入的baseUrl,和api创建retrofit */ private static <T> T createApi(Class<T> clazz, String baseUrl) { Retrofit retrofit = new Retrofit.Builder() .baseUrl(baseUrl) .client(mOkHttpClient) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build(); return retrofit.create(clazz); }
private VideoApiManager(){ HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(message -> showRetrofitLog(message)).setLevel(HttpLoggingInterceptor.Level.BODY);//打印请求日志 OkHttpClient okHttpClient = new OkHttpClient.Builder() .readTimeout(READ_TIME_OUT, TimeUnit.SECONDS) .connectTimeout(CONNECT_TIME_OUT,TimeUnit.SECONDS) .addInterceptor(loggingInterceptor) .build(); Retrofit retrofit1 = new Retrofit.Builder() .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .baseUrl(Constant.Video_BASE_URL) .build(); videoApiService = retrofit1.create(VideoApi.class); }
private Api(Builder builder) { OkHttpClient.Builder okBuilder = new OkHttpClient.Builder() .readTimeout(builder.readTimeout, builder.timeUnit) .connectTimeout(builder.connectTimeout, builder.timeUnit) .addInterceptor(getHttpLoggingInterceptor(builder.logLevel)); if (builder.isCache) { okBuilder = okBuilder.cache(new Cache(builder.cachefile, builder.cachelength)) .addNetworkInterceptor(new HttpCacheInterceptor()); } if (builder.interceptors != null) { for (int i = 0; i < builder.interceptors.size(); i++) { okBuilder.addInterceptor(builder.interceptors.get(i)); } } if (builder.isAddTokenInterceptor) { okBuilder.addInterceptor(new TokenInterceptor()); } retrofit = new Retrofit.Builder() .client(okBuilder.build()) .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().setLenient().create())) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .baseUrl(builder.baseUrl) .build(); }
@Provides @Singleton Retrofit provideRetrofit(GsonConverterFactory gson, OkHttpClient okHttpClient) { return new Retrofit.Builder() .baseUrl(BuildConfig.API_URL) .addConverterFactory(gson) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addCallAdapterFactory(LiveDataCallAdapterFactory.create()) .client(okHttpClient) .build(); }
/** * 网络请求 * * @param weatherId */ private void requestWeather(final String weatherId) { new Retrofit.Builder() .baseUrl("https://free-api.heweather.com/v5/") .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build() .create(WeatherApi.class) .getWeather(weatherId, KEY) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<HeWeather5>() { @Override public void onCompleted() { loadDatas(); } @Override public void onError(Throwable e) { view.stopLoading(); view.showError(); } @Override public void onNext(HeWeather5 heWeather5) { Weather weather = heWeather5.getHeWeather5().get(0); if (weather != null && "ok".equals(weather.status)) { SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit(); editor.putString("weather", gson.toJson(weather)); editor.apply(); } } }); loadBingPic(); }
@Provides @Singleton public Retrofit provideRestAdapter(OkHttpClient okHttpClient) { return new Retrofit.Builder() .baseUrl(ApiService.ENDPOINT) .addConverterFactory(GsonConverterFactory.create()) .client(okHttpClient) .build(); }
@Provides @Singleton @ImaggaRetrofit Retrofit provideImaggaRetrofit(@ImaggaBaseUrl String imaggaBaseUrl,GsonConverterFactory gsonConverterFactory, RxJava2CallAdapterFactory rxJava2CallAdapterFactory, OkHttpClient okHttpClient) { return new Retrofit.Builder() .baseUrl(imaggaBaseUrl) .addConverterFactory(gsonConverterFactory) .addCallAdapterFactory(rxJava2CallAdapterFactory) .client(okHttpClient) .build(); }