retrofit2.converter.scalars.ScalarsConverterFactory Java Examples

The following examples show how to use retrofit2.converter.scalars.ScalarsConverterFactory. 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: RetrofitCircuitBreakerTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
    this.circuitBreaker = CircuitBreaker.of("test", circuitBreakerConfig);

    final long TIMEOUT = 150; // ms
    this.client = new OkHttpClient.Builder()
        .connectTimeout(TIMEOUT, TimeUnit.MILLISECONDS)
        .readTimeout(TIMEOUT, TimeUnit.MILLISECONDS)
        .writeTimeout(TIMEOUT, TimeUnit.MILLISECONDS)
        .build();

    this.service = new Retrofit.Builder()
        .addCallAdapterFactory(CircuitBreakerCallAdapter.of(circuitBreaker))
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .addConverterFactory(ScalarsConverterFactory.create())
        .baseUrl(wireMockRule.baseUrl())
        .client(client)
        .build()
        .create(RetrofitService.class);
}
 
Example #2
Source File: RetrofitFactory.java    From TigerVideo with Apache License 2.0 6 votes vote down vote up
private static IFengApi createIFengService() {

        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(TIME_OUT, TimeUnit.SECONDS)
                .readTimeout(TIME_OUT, TimeUnit.SECONDS)
                .writeTimeout(TIME_OUT, TimeUnit.SECONDS)
                .addInterceptor(new HttpLoggingInterceptor()
                .setLevel(HttpLoggingInterceptor.Level.BODY))
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(IFENG_BASE_URL)
                .client(client)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        return retrofit.create(IFengApi.class);
    }
 
Example #3
Source File: RetrofitActivity.java    From AndroidSamples with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_retrofit);
    ButterKnife.bind(this);
    //01:获取Retrofit对象
    mRetrofit = new Retrofit.Builder()
            //02采用链式结构绑定Base url
            .baseUrl(ApiStores.API_SERVER_URL)
            // 注意:字符创解析器要放在Gson解析器前面,不然无法解析字符串
            //使用工厂模式创建字符串解析器
            .addConverterFactory(ScalarsConverterFactory.create())
            //使用工厂模式创建Gson的解析器
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    //04获取API接口的实现类的实例对象
    mApiStores = mRetrofit.create(ApiStores.class);

}
 
Example #4
Source File: HttpDownLoadManager.java    From TestChat with Apache License 2.0 6 votes vote down vote up
public void start(final DownInfo info) {
//                如果消息实体为空,或正在下载,则返回
                if (info == null || mDownInfoMap.get(info.getUrl()) != null) return;
                DownLoadSubscriber<DownInfo> downLoadSubscriber = new DownLoadSubscriber<>(info);
                mDownInfoMap.put(info.getUrl(), downLoadSubscriber);
//                HttpService service;
//                增加一个拦截器,用于获取数据的进度回调
                DownLoadInterceptor interceptor = new DownLoadInterceptor(downLoadSubscriber);
                OkHttpClient.Builder builder = new OkHttpClient.Builder();
                builder.connectTimeout(info.getConnectedTime(), TimeUnit.SECONDS).addInterceptor(interceptor);
                Retrofit retrofit = new Retrofit.Builder().
                        addConverterFactory(ScalarsConverterFactory.create()).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).
                        baseUrl(CommonUtils.getBaseUrl(info.getUrl())).client(builder.build()).build();
                HttpService service = retrofit.create(HttpService.class);
                info.setHttpService(service);
                service.download("bytes=" + info.getReadLength() + "-", info.getUrl()).subscribeOn(Schedulers.io())
                        .unsubscribeOn(Schedulers.io()).retryWhen(new RetryWhenNetWorkException()).map(new Func1<ResponseBody, DownInfo>() {
                        @Override
                        public DownInfo call(ResponseBody responseBody) {
                                FileUtil.writeToCache(responseBody, info.getSavedFilePath(), info.getReadLength(), info.getTotalLength());
//                                这里进行转化
                                return info;
                        }
                }).observeOn(AndroidSchedulers.mainThread()).subscribe(downLoadSubscriber);
        }
 
Example #5
Source File: HttpManager.java    From RxjavaRetrofitDemo-string-master with MIT License 6 votes vote down vote up
/**
 * 获取Retrofit对象
 *
 * @param basePar
 * @return
 */
public Retrofit getReTrofit(final BaseApi basePar) {
    //手动创建一个OkHttpClient并设置超时时间缓存等设置
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    builder.connectTimeout(basePar.getConnectionTime(), TimeUnit.SECONDS);
    if (RxRetrofitApp.isDebug()) {
        builder.addInterceptor(getHttpLoggingInterceptor());
    }

    /*创建retrofit对象*/
    final Retrofit retrofit = new Retrofit.Builder()
            .client(builder.build())
            .addConverterFactory(ScalarsConverterFactory.create())
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .baseUrl(basePar.getBaseUrl())
            .build();
    return retrofit;
}
 
Example #6
Source File: ApiClient.java    From Learning-Resources with MIT License 6 votes vote down vote up
/**
 * You can create multiple methods for different BaseURL
 *
 * @return {@link Retrofit} object
 */
public static Retrofit getClient() {
    if (retrofit == null) {
        Gson gson = new GsonBuilder()
                .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
                .create();

        retrofit = new Retrofit.Builder()
                .baseUrl(WebService.BaseLink + WebService.Version)
                .client(getOKHttpClient())
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addConverterFactory(ScalarsConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
    }
    return retrofit;
}
 
Example #7
Source File: NetService.java    From easyweather with MIT License 6 votes vote down vote up
public NetService init(String baseUrl) {
    synchronized (this) {
        if (baseUrl.charAt(baseUrl.length() - 1) != '/'){
            baseUrl = baseUrl + "/";
        }
        okHttpClient = new OkHttpClient.Builder().
                readTimeout(15, TimeUnit.SECONDS).
                writeTimeout(10, TimeUnit.SECONDS).
                connectTimeout(10, TimeUnit.SECONDS).
                addInterceptor(loggingInterceptor).
                build();

        retrofit = new Retrofit.Builder().
                addConverterFactory(ScalarsConverterFactory.create()).
                addConverterFactory(GsonConverterFactory.create()).
                addCallAdapterFactory(RxJavaCallAdapterFactory.create()).
                baseUrl(baseUrl).
                client(okHttpClient).
                build();
        downLoadService = create(IDownLoadService.class);

    }
    return this;
}
 
Example #8
Source File: NetService.java    From easyweather with MIT License 6 votes vote down vote up
public NetService init(String baseurl, Map<String, String> headers) {
    synchronized (this) {
        headerInterceptor = new HeaderInterceptor(headers);
        okHttpClient = new OkHttpClient.Builder().
                readTimeout(15, TimeUnit.SECONDS).
                writeTimeout(10, TimeUnit.SECONDS).
                connectTimeout(10, TimeUnit.SECONDS).
                addInterceptor(loggingInterceptor).
                addInterceptor(headerInterceptor).
                build();

        retrofit = new Retrofit.Builder().
                addConverterFactory(ScalarsConverterFactory.create()).
                addConverterFactory(GsonConverterFactory.create()).
                addCallAdapterFactory(RxJavaCallAdapterFactory.create()).
                baseUrl(baseurl).
                client(okHttpClient).
                build();
        downLoadService = create(IDownLoadService.class);

    }
    return this;
}
 
Example #9
Source File: CommonHttpManager.java    From TestChat with Apache License 2.0 6 votes vote down vote up
public void dealApiReqest(BaseApi baseApi) {
//                创建一个OkHttpClient
                OkHttpClient.Builder builder = new OkHttpClient.Builder();
                CommonSubscriber commonSubscriber = new CommonSubscriber(baseApi, mOnNextListenerSoftReference, mRxAppCompatActivitySoftReference);
                builder.addInterceptor(new CacheInterceptor()).connectTimeout(baseApi.getConnectedTime(), TimeUnit.SECONDS)
                        .writeTimeout(baseApi.getWritedOutTime(), TimeUnit.SECONDS).addNetworkInterceptor(new CacheInterceptor())
                        .cache(new Cache(CustomApplication.getInstance().getCacheDir(), 10 * 1024 * 1024));
                Retrofit retrofit = new Retrofit.Builder().client(builder.build()).baseUrl(baseApi.getBaseUrl()).addConverterFactory(ScalarsConverterFactory.create())
                        .addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();
//                        .build();
//                这里原理是通过Java的动态代理创建接口的实例
                HttpService httpService = retrofit.create(HttpService.class);
                Observable observable = baseApi.getObservable(httpService);
                observable.retryWhen(new RetryWhenNetWorkException()).subscribeOn(Schedulers.io()).unsubscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()).map(baseApi).subscribe(commonSubscriber);
        }
 
Example #10
Source File: RetrofitFactory.java    From TigerVideo with Apache License 2.0 6 votes vote down vote up
private static TtKbApi createTtKbService() {

        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(TIME_OUT, TimeUnit.SECONDS)
                .readTimeout(TIME_OUT, TimeUnit.SECONDS)
                .writeTimeout(TIME_OUT, TimeUnit.SECONDS)
                .addInterceptor(new HttpLoggingInterceptor()
                .setLevel(HttpLoggingInterceptor.Level.BODY))
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(TTKB_BASE_URL)
                .client(client)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        return retrofit.create(TtKbApi.class);
    }
 
Example #11
Source File: RetrofitFactory.java    From TigerVideo with Apache License 2.0 6 votes vote down vote up
private static NetEasyApi createNetEasyService() {

        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(TIME_OUT, TimeUnit.SECONDS)
                .readTimeout(TIME_OUT, TimeUnit.SECONDS)
                .writeTimeout(TIME_OUT, TimeUnit.SECONDS)
                .addInterceptor(new HttpLoggingInterceptor()
                .setLevel(HttpLoggingInterceptor.Level.BODY))
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(NETEASY_BASE_URL)
                .client(client)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        return retrofit.create(NetEasyApi.class);
    }
 
Example #12
Source File: HttpUtil.java    From Focus with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 返回retrofit的实体对象
 * @param readTimeout
 * @param writeTimeout
 * @param connectTimeout
 * @return
 */
public static Retrofit getRetrofit(String type, String requestUrl, int readTimeout, int writeTimeout, int connectTimeout){
    Converter.Factory factory = null;
    if (type.equals("String")){
        factory = ScalarsConverterFactory.create();
    }else if (type.equals("bean")){
        factory = JacksonConverterFactory.create();
    }

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(requestUrl)
            .client(HttpUtil.getOkHttpClient(type,readTimeout,writeTimeout,connectTimeout))
            .addConverterFactory(factory)//retrofit已经把Json解析封装在内部了 你需要传入你想要的解析工具就行了
            .build();
    return retrofit;
}
 
Example #13
Source File: ApiClient.java    From androidMvvm with MIT License 6 votes vote down vote up
public static Retrofit getClientAuthentication() {
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
// set your desired log level
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        Retrofit.Builder builder = new Retrofit.Builder()
                .baseUrl(URL_BASE);
        AuthenticationInterceptor interceptor = new AuthenticationInterceptor(
                Credentials.basic("", ""));
        if (!httpClient.interceptors().contains(interceptor)) {
            httpClient.addInterceptor(interceptor);
            httpClient.addInterceptor(logging);
            builder.client(httpClient.build());
            retrofit = builder
                    // .baseUrl(URL_BASE)
                    .addConverterFactory(ScalarsConverterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(httpClient.build())
                    .build();

        }

        return retrofit;
    }
 
Example #14
Source File: RetrofitCircuitBreakerTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldDelegateToOtherAdapter() {
    String body = "this is from rxjava";

    stubFor(get(urlPathEqualTo("/delegated"))
        .willReturn(aResponse()
            .withStatus(200)
            .withHeader("Content-Type", "text/plain")
            .withBody(body)));

    RetrofitService service = new Retrofit.Builder()
        .addCallAdapterFactory(CircuitBreakerCallAdapter.of(circuitBreaker))
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .addConverterFactory(ScalarsConverterFactory.create())
        .baseUrl(wireMockRule.baseUrl())
        .client(client)
        .build()
        .create(RetrofitService.class);

    String resultBody = service.delegated().blockingGet();
    assertThat(resultBody).isEqualTo(body);
    verify(1, getRequestedFor(urlPathEqualTo("/delegated")));

    final CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics();
    assertThat(metrics.getNumberOfSuccessfulCalls()).isEqualTo(1);
}
 
Example #15
Source File: ServicesManager.java    From LittleFreshWeather with Apache License 2.0 6 votes vote down vote up
private ServicesManager() {
    List<Protocol> protocols = new ArrayList<Protocol>();
    protocols.add(Protocol.HTTP_1_1);
    protocols.add(Protocol.HTTP_2);

    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
    builder.protocols(protocols);

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Constants.WEATHER_BASE_URL)
            .client(builder.build())
            .addConverterFactory(ScalarsConverterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .build();
    weatherInfoService = retrofit.create(WeatherInfoService.class);

    mNameMap.put("CN10101", "北京");
    mNameMap.put("CN10102", "上海");
    mNameMap.put("CN10103", "天津");
    mNameMap.put("CN10104", "重庆");
    mNameMap.put("CN10132", "香港");
    mNameMap.put("CN10133", "澳门");
}
 
Example #16
Source File: RetrofitRateLimiterTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
    final long TIMEOUT = 150; // ms
    this.client = new OkHttpClient.Builder()
        .connectTimeout(TIMEOUT, TimeUnit.MILLISECONDS)
        .readTimeout(TIMEOUT, TimeUnit.MILLISECONDS)
        .writeTimeout(TIMEOUT, TimeUnit.MILLISECONDS)
        .build();

    this.rateLimiter = RateLimiter.of("backendName", config);
    this.service = new Retrofit.Builder()
        .addCallAdapterFactory(RateLimiterCallAdapter.of(rateLimiter))
        .addConverterFactory(ScalarsConverterFactory.create())
        .client(client)
        .baseUrl(wireMockRule.baseUrl())
        .build()
        .create(RetrofitService.class);
}
 
Example #17
Source File: NetUtils.java    From MVPDemo with Apache License 2.0 6 votes vote down vote up
public static Retrofit getRetrofit() {
    if (retrofit == null) {
        synchronized (NetUtils.class) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(mBaseUrl)
                    //增加返回值为String的支持
                    .addConverterFactory(ScalarsConverterFactory.create())
                    //增加返回值为Gson的支持(以实体类返回)
                    .addConverterFactory(GsonConverterFactory.create())
                    //增加返回值为Oservable<T>的支持
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .client(getOkHttpClient())
                    .build();
        }
    }
    return retrofit;
}
 
Example #18
Source File: HttpUtil.java    From Focus with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 返回retrofit的实体对象
 * @param readTimeout
 * @param writeTimeout
 * @param connectTimeout
 * @return
 */
public static Retrofit getRetrofit(String type, String requestUrl, int readTimeout, int writeTimeout, int connectTimeout){
    Converter.Factory factory = null;
    if (type.equals("String")){
        factory = ScalarsConverterFactory.create();
    }else if (type.equals("bean")){
        factory = JacksonConverterFactory.create();
    }

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(requestUrl)
            .client(HttpUtil.getOkHttpClient(type,readTimeout,writeTimeout,connectTimeout))
            .addConverterFactory(factory)//retrofit已经把Json解析封装在内部了 你需要传入你想要的解析工具就行了
            .build();
    return retrofit;
}
 
Example #19
Source File: ApiClient.java    From devicehive-java with Apache License 2.0 6 votes vote down vote up
private void createDefaultAdapter(String url) {
    DateTimeTypeAdapter typeAdapter = new DateTimeTypeAdapter(Const.TIMESTAMP_FORMAT);
    Gson gson = new GsonBuilder()
            .registerTypeAdapter(DateTime.class,
                    typeAdapter)
            .create();
    okClient = new OkHttpClient().newBuilder()
            .readTimeout(35, TimeUnit.SECONDS)
            .connectTimeout(35, TimeUnit.SECONDS)
            .build();

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

    adapterBuilder = new Retrofit
            .Builder()
            .baseUrl(url)
            .client(okClient)
            .addConverterFactory(ScalarsConverterFactory.create())
            .addConverterFactory(GsonCustomConverterFactory.create(gson));

}
 
Example #20
Source File: RetrofitCircuitBreakerTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotDelegateToOtherAdapterWhenAddedAfterwards() {
    String body = "this is from rxjava";

    stubFor(get(urlPathEqualTo("/delegated"))
        .willReturn(aResponse()
            .withStatus(200)
            .withHeader("Content-Type", "text/plain")
            .withBody(body)));

    RetrofitService service = new Retrofit.Builder()
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .addCallAdapterFactory(CircuitBreakerCallAdapter.of(circuitBreaker))
        .addConverterFactory(ScalarsConverterFactory.create())
        .baseUrl(wireMockRule.baseUrl())
        .client(client)
        .build()
        .create(RetrofitService.class);

    String resultBody = service.delegated().blockingGet();
    assertThat(resultBody).isEqualTo(body);
    verify(1, getRequestedFor(urlPathEqualTo("/delegated")));

    // No metrics should exist because circuit breaker wasn't used
    final CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics();
    assertThat(metrics.getNumberOfSuccessfulCalls()).isEqualTo(0);
    assertThat(metrics.getNumberOfFailedCalls()).isEqualTo(0);
    assertThat(metrics.getNumberOfNotPermittedCalls()).isEqualTo(0);
    assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(0);
}
 
Example #21
Source File: RetrofitRateLimiterTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotDelegateToOtherAdapterWhenAddedAfterwards() {
    String body = "this is from rxjava";

    stubFor(get(urlPathEqualTo("/delegated"))
        .willReturn(aResponse()
            .withStatus(200)
            .withHeader("Content-Type", "text/plain")
            .withBody(body)));

    RetrofitService service = new Retrofit.Builder()
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .addCallAdapterFactory(RateLimiterCallAdapter.of(RateLimiter.of(
            "backendName",
            RateLimiterConfig.custom()
                .timeoutDuration(Duration.ofMillis(50))
                .limitForPeriod(1)
                .limitRefreshPeriod(Duration.ofDays(1))
                .build()
        )))
        .addConverterFactory(ScalarsConverterFactory.create())
        .client(client)
        .baseUrl(wireMockRule.baseUrl())
        .build()
        .create(RetrofitService.class);

    Single<String> success = service.delegated();
    Single<String> failure = service.delegated();

    String resultBody = success.blockingGet();
    failure.blockingGet();

    assertThat(resultBody).isEqualTo(body);
    verify(2, getRequestedFor(urlPathEqualTo("/delegated")));
}
 
Example #22
Source File: ClueCommandClient.java    From clue with Apache License 2.0 5 votes vote down vote up
public ClueCommandClient(URL url) throws Exception {
    final OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    if ("https".equals(url.getProtocol())) {
        try {
            setSslSocketFactory(okHttpClientBuilder);
        } catch(Exception e) {
            throw new IllegalStateException("cannot create ssl connection: " + e);
        }
    }

    final OkHttpClient okHttpClient = okHttpClientBuilder.readTimeout(10, TimeUnit.SECONDS)
            .connectTimeout(10, TimeUnit.SECONDS)
            .build();

    Retrofit restAdator = new Retrofit.Builder().baseUrl(HttpUrl.get(url))
            .addConverterFactory(ScalarsConverterFactory.create())
            .addConverterFactory(JacksonConverterFactory.create(mapper))
            .client(okHttpClient).build();

    svc = restAdator.create(ClueCommandService.class);

    cmdlineHelper = new CmdlineHelper(new Supplier<Collection<String>>() {
        @Override
        public Collection<String> get() {
            try {
                return getCommands();
            } catch (Exception e) {
                System.out.println("unable obtaining command list");
                return Collections.emptyList();
            }
        }
    }, null);
}
 
Example #23
Source File: RetrofitRateLimiterTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldDelegateToOtherAdapter() {
    String body = "this is from rxjava";

    stubFor(get(urlPathEqualTo("/delegated"))
        .willReturn(aResponse()
            .withStatus(200)
            .withHeader("Content-Type", "text/plain")
            .withBody(body)));

    RetrofitService service = new Retrofit.Builder()
        .addCallAdapterFactory(RateLimiterCallAdapter.of(RateLimiter.of(
            "backendName",
            RateLimiterConfig.custom()
                .timeoutDuration(Duration.ofMillis(50))
                .limitForPeriod(1)
                .limitRefreshPeriod(Duration.ofDays(1))
                .build()
        )))
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .addConverterFactory(ScalarsConverterFactory.create())
        .client(client)
        .baseUrl(wireMockRule.baseUrl())
        .build()
        .create(RetrofitService.class);

    Single<String> success = service.delegated();
    Single<String> failure = service.delegated();

    String resultBody = success.blockingGet();
    try {
        failure.blockingGet();
        fail("Expected HttpException to be thrown");
    } catch (HttpException httpe) {
        assertThat(httpe.code()).isEqualTo(429);
    }

    assertThat(resultBody).isEqualTo(body);
    verify(1, getRequestedFor(urlPathEqualTo("/delegated")));
}
 
Example #24
Source File: HttpManager.java    From RxRetrofit-mvp with MIT License 5 votes vote down vote up
/**
     * 处理http请求
     *
     * @param basePar 封装的请求数据
     */
    public void doHttpDeal(BaseApi basePar) {
        //手动创建一个OkHttpClient并设置超时时间缓存等设置
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(basePar.getConnectionTime(), TimeUnit.SECONDS);

        /*创建retrofit对象*/
        Retrofit retrofit = new Retrofit.Builder()
                .client(builder.build())
                .addConverterFactory(ScalarsConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(basePar.getBaseUrl())
                .build();
        /*rx处理*/
        ProgressSubscriber subscriber = new ProgressSubscriber(basePar, onNextListener);

        Observable observable = basePar.getObservable(retrofit)
                /*失败后的retry配置*/
                .retryWhen(new RetryWhenNetworkException())
                /*异常处理*/
                .onErrorResumeNext(funcException)
                /*生命周期管理*/
//                .compose(appCompatActivity.get().bindToLifecycle())
                .compose(appCompatActivity.get().bindUntilEvent(ActivityEvent.DESTROY))
                /*http请求线程*/
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                /*回调线程*/
                .observeOn(AndroidSchedulers.mainThread())
                /*结果判断*/
                .map(basePar);

        /*数据回调*/
        observable.subscribe(subscriber);
    }
 
Example #25
Source File: ServiceGenerator.java    From XposedSmsCode with GNU General Public License v3.0 5 votes vote down vote up
public <T> T createService(String baseUrl, Class<T> serviceClass) {
    Retrofit retrofit = mRetrofitMap.get(baseUrl);
    if (retrofit == null) {
        retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(mOkHttpClient)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        mRetrofitMap.put(baseUrl, retrofit);
    }
    return retrofit.create(serviceClass);
}
 
Example #26
Source File: HttpDownLoadManager.java    From TestChat with Apache License 2.0 5 votes vote down vote up
public void start(final DownInfo info) {
//                如果消息实体为空,或正在下载,则返回
                LogUtil.e("开始下载1");
                if (info == null || mDownInfoMap.get(info.getUrl()) != null) return;
                DownLoadSubscriber downLoadSubscriber = new DownLoadSubscriber(info);
                mDownInfoMap.put(info.getUrl(), downLoadSubscriber);
//                HttpService service;
//                增加一个拦截器,用于获取数据的进度回调
                DownLoadInterceptor interceptor = new DownLoadInterceptor(downLoadSubscriber);
                OkHttpClient.Builder builder = new OkHttpClient.Builder();
                builder.connectTimeout(info.getConnectedTime(), TimeUnit.SECONDS).addInterceptor(interceptor);
                Retrofit retrofit = new Retrofit.Builder().
                        addConverterFactory(ScalarsConverterFactory.create()).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).
                        baseUrl("http://bmob-cdn-7375.b0.upaiyun.com/").client(builder.build()).build();
                HttpService service = retrofit.create(HttpService.class);
//                info.setHttpService(service);
                service.download().subscribeOn(Schedulers.io())
                        .unsubscribeOn(Schedulers.io()).map(new Func1<ResponseBody, DownInfo>() {
                        @Override
                        public DownInfo call(ResponseBody responseBody) {
                                LogUtil.e("call");
                                if (responseBody != null) {
                                        LogUtil.e("ewsponseBody  is not null");
                                }
                                FileUtil.writeToCache(responseBody, info.getSavedFilePath(), info.getReadLength(), info.getTotalLength());
//                                这里进行转化
                                return info;
                        }
                }).observeOn(AndroidSchedulers.mainThread()).subscribe(downLoadSubscriber);
        }
 
Example #27
Source File: RxHttpConfig.java    From XKnife-Android with Apache License 2.0 5 votes vote down vote up
/**
 * 默认配置
 *
 * @param baseUrl the base url
 * @param logger  the logger
 * @return the rx http config
 */
public static RxHttpConfig createDefault(String baseUrl, boolean logger) {
    Builder builder = new Builder();
    if (logger) {
        builder.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC));
    }
    return builder.baseUrl(baseUrl)
            .connectTimeout(DEFAULT_CONNECT_TIMEOUT)
            .addConverterFactory(ScalarsConverterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .build();
}
 
Example #28
Source File: ServiceProvider.java    From homeassist with Apache License 2.0 5 votes vote down vote up
public static RestAPIService getRawApiService(final String baseUrl) {
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(baseUrl)
            .addConverterFactory(ScalarsConverterFactory.create())
            .client(getOkHttpClientInstance(DEFAULT_READ_TIMEOUT_IN_SEC))
            .build();
    return retrofit.create(RestAPIService.class);
}
 
Example #29
Source File: NetUtils.java    From MVPDemo with Apache License 2.0 5 votes vote down vote up
public static Retrofit getRetrofit(String baseUrl) {
    mRetrofit = new Retrofit.Builder()
            .baseUrl(baseUrl)
            //增加返回值为String的支持
            .addConverterFactory(ScalarsConverterFactory.create())
            //增加返回值为Gson的支持(以实体类返回)
            .addConverterFactory(GsonConverterFactory.create())
            //增加返回值为Oservable<T>的支持
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .client(getOkHttpClient())
            .build();
    return mRetrofit;
}
 
Example #30
Source File: NetModule.java    From WanAndroid with GNU General Public License v3.0 5 votes vote down vote up
@Singleton
@Provides
static API provideAPI(OkHttpClient client) {
    return new Retrofit.Builder()
            .baseUrl(BuildConfig.BASE_URL)
            .addConverterFactory(ScalarsConverterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .client(client)
            .build()
            .create(API.class);
}