use of retrofit2.http.Header in project Awesome-WanAndroid by JsonChao.
the class HttpModule method provideClient.
@Singleton
@Provides
OkHttpClient provideClient(OkHttpClient.Builder builder) {
if (BuildConfig.DEBUG) {
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
builder.addInterceptor(loggingInterceptor);
}
File cacheFile = new File(Constants.PATH_CACHE);
Cache cache = new Cache(cacheFile, 1024 * 1024 * 50);
Interceptor cacheInterceptor = chain -> {
Request request = chain.request();
if (!CommonUtils.isNetworkConnected()) {
request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
}
Response response = chain.proceed(request);
if (CommonUtils.isNetworkConnected()) {
int maxAge = 0;
// 有网络时, 不缓存, 最大保存时长为0
response.newBuilder().header("Cache-Control", "public, max-age=" + maxAge).removeHeader("Pragma").build();
} else {
// 无网络时,设置超时为4周
int maxStale = 60 * 60 * 24 * 28;
response.newBuilder().header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale).removeHeader("Pragma").build();
}
return response;
};
// 设置缓存
builder.addNetworkInterceptor(cacheInterceptor);
builder.addInterceptor(cacheInterceptor);
builder.cache(cache);
// 设置超时
builder.connectTimeout(10, TimeUnit.SECONDS);
builder.readTimeout(20, TimeUnit.SECONDS);
builder.writeTimeout(20, TimeUnit.SECONDS);
// 错误重连
builder.retryOnConnectionFailure(true);
// cookie认证
builder.cookieJar(new CookiesManager());
return builder.build();
}
use of retrofit2.http.Header in project android-diplicity by zond.
the class RetrofitActivity method onActivityResult.
@Override
protected void onActivityResult(final int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == LOGIN_REQUEST) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result != null) {
if (result.isSuccess()) {
final GoogleSignInAccount acct = result.getSignInAccount();
Observable.create(new Observable.OnSubscribe<String>() {
@Override
public void call(final Subscriber<? super String> subscriber) {
Response response = null;
try {
String url = getBaseURL() + "Auth/OAuth2Callback?code=" + URLEncoder.encode(acct.getServerAuthCode(), "UTF-8") + "&approve-redirect=true&state=" + URLEncoder.encode("https://android-diplicity", "UTF-8");
Request request = new Request.Builder().url(url).build();
response = new OkHttpClient.Builder().followRedirects(false).followSslRedirects(false).connectTimeout(10, TimeUnit.SECONDS).readTimeout(10, TimeUnit.SECONDS).writeTimeout(10, TimeUnit.SECONDS).build().newCall(request).execute();
if (response.code() != 307) {
throw new RuntimeException("Unsuccessful response " + response.body().string());
}
url = response.headers().get("Location");
if (url == null) {
throw new RuntimeException("No Location header in response " + response.body().string());
}
Uri parsedURI = Uri.parse(url);
if (parsedURI == null) {
throw new RuntimeException("Unparseable Location header " + url + " in response");
}
subscriber.onNext(parsedURI.getQueryParameter("token"));
subscriber.onCompleted();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
App.firebaseCrashReport("Unable to log in", e);
Toast.makeText(RetrofitActivity.this, R.string.login_failed, Toast.LENGTH_SHORT).show();
}
@Override
public void onNext(String token) {
PreferenceManager.getDefaultSharedPreferences(RetrofitActivity.this).edit().putString(AUTH_TOKEN_PREF_KEY, token).apply();
performLogin();
}
});
} else {
App.firebaseCrashReport("Login failed: " + result.getStatus().getStatus());
Toast.makeText(this, R.string.login_failed, Toast.LENGTH_SHORT).show();
}
} else {
App.firebaseCrashReport("Login failed, null result");
Toast.makeText(this, R.string.login_failed, Toast.LENGTH_SHORT).show();
}
}
}
use of retrofit2.http.Header in project autorest.java by Azure.
the class HeadersImpl method paramDatetimeRfc1123WithServiceResponseAsync.
/**
* Send a post request with header values "scenario": "valid", "value": "Wed, 01 Jan 2010 12:34:56 GMT" or "scenario": "min", "value": "Mon, 01 Jan 0001 00:00:00 GMT".
*
* @param scenario Send a post request with header values "scenario": "valid" or "min"
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceResponse} object if successful.
*/
public Observable<ServiceResponse<Void>> paramDatetimeRfc1123WithServiceResponseAsync(String scenario) {
if (scenario == null) {
throw new IllegalArgumentException("Parameter scenario is required and cannot be null.");
}
final DateTime value = null;
DateTimeRfc1123 valueConverted = null;
if (value != null) {
valueConverted = new DateTimeRfc1123(value);
}
return service.paramDatetimeRfc1123(scenario, valueConverted).flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() {
@Override
public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) {
try {
ServiceResponse<Void> clientResponse = paramDatetimeRfc1123Delegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
use of retrofit2.http.Header in project autorest.java by Azure.
the class LRORetrysImpl method putAsyncRelativeRetrySucceededWithServiceResponseAsync.
/**
* Long running put request, service returns a 500, then a 200 to the initial request, with an entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status.
*
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
public Observable<ServiceResponseWithHeaders<Product, LRORetrysPutAsyncRelativeRetrySucceededHeaders>> putAsyncRelativeRetrySucceededWithServiceResponseAsync() {
final Product product = null;
Observable<Response<ResponseBody>> observable = service.putAsyncRelativeRetrySucceeded(product, this.client.acceptLanguage(), this.client.userAgent());
return client.getAzureClient().getPutOrPatchResultWithHeadersAsync(observable, new TypeToken<Product>() {
}.getType(), LRORetrysPutAsyncRelativeRetrySucceededHeaders.class);
}
use of retrofit2.http.Header in project autorest.java by Azure.
the class LRORetrysImpl method postAsyncRelativeRetrySucceededWithServiceResponseAsync.
/**
* Long running post request, service returns a 500, then a 202 to the initial request, with an entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status.
*
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
public Observable<ServiceResponseWithHeaders<Void, LRORetrysPostAsyncRelativeRetrySucceededHeaders>> postAsyncRelativeRetrySucceededWithServiceResponseAsync() {
final Product product = null;
Observable<Response<ResponseBody>> observable = service.postAsyncRelativeRetrySucceeded(product, this.client.acceptLanguage(), this.client.userAgent());
return client.getAzureClient().getPostOrDeleteResultWithHeadersAsync(observable, new TypeToken<Void>() {
}.getType(), LRORetrysPostAsyncRelativeRetrySucceededHeaders.class);
}
Aggregations